{"text":"\/*=========================================================================\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 \n#include \n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n#include \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 *\/\nCOMP: Fixed bad #if defined( _DEBUG ) statement.\/*=========================================================================\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 \n#include \n\n\/\/\n\/\/ System includes (sorted by alphabetic order)\n#include \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":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 OpInfoMap;\n typedef std::map 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 Split(const std::string& s, char delim) {\n std::vector 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 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 > 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& children = child_map[qual_name];\n for (std::vector::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& children = child_map[o->first];\n for (std::vector::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 \n std::vector SortOpInfo(const OpInfoMap& op_info_map, CmpFunc cmp) {\n std::vector 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 op_info = SortOpInfo(f->second, sort_by_func);\n for (std::vector::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}\nHalideProf should check the entire line for \"halide_profiler\" tag.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 OpInfoMap;\n typedef std::map 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 Split(const std::string& s, char delim) {\n std::vector 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 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 > 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& children = child_map[qual_name];\n for (std::vector::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& children = child_map[o->first];\n for (std::vector::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 \n std::vector SortOpInfo(const OpInfoMap& op_info_map, CmpFunc cmp) {\n std::vector 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 op_info = SortOpInfo(f->second, sort_by_func);\n for (std::vector::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":"#include \n\n#include \n#include \n#include \n#include \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}\nBUGFIX: error in building up a file location might occur, if we do not check for a correct usage of slashes#include \n\n#include \n#include \n#include \n#include \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":"\/*************************************************************************\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 \n#endif\n#ifndef _COM_SUN_STAR_EMBED_ENTRYINITMODES_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n\n#include \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\nINTEGRATION: 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\/*************************************************************************\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 \n#endif\n#ifndef _COM_SUN_STAR_EMBED_ENTRYINITMODES_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n\n#include \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":"\/*******************************************************************************\n * src\/benchmark.cpp\n *\n * Copyright (C) 2017 Florian Kurpicz \n *\n * All rights reserved. Published under the BSD-2 license in the LICENSE file.\n ******************************************************************************\/\n\n#include \n#include \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 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 \\n\"\n \" Marvin Löbel \");\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 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 text_uint8;\n std::vector text_uint16;\n std::vector text_uint32;\n std::vector 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 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\/******************************************************************************\/\nFix naming in benchmark.cpp\/*******************************************************************************\n * src\/benchmark.cpp\n *\n * Copyright (C) 2017 Florian Kurpicz \n *\n * All rights reserved. Published under the BSD-2 license in the LICENSE file.\n ******************************************************************************\/\n\n#include \n#include \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 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 \\n\"\n \" Marvin Löbel \");\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 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 text_uint8;\n std::vector text_uint16;\n std::vector text_uint32;\n std::vector 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 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":"\/*******************************************************************************\n * src\/benchmark.cpp\n *\n * Copyright (C) 2017 Florian Kurpicz \n *\n * All rights reserved. Published under the BSD-2 license in the LICENSE file.\n ******************************************************************************\/\n\n#include \n#include \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 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 \\n\"\n \" Marvin Löbel \");\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 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 text_uint8;\n std::vector text_uint16;\n std::vector text_uint32;\n std::vector 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\/******************************************************************************\/\nAdd filter for huffman-shaped algorithms\/*******************************************************************************\n * src\/benchmark.cpp\n *\n * Copyright (C) 2017 Florian Kurpicz \n *\n * All rights reserved. Published under the BSD-2 license in the LICENSE file.\n ******************************************************************************\/\n\n#include \n#include \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 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 \\n\"\n \" Marvin Löbel \");\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 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 text_uint8;\n std::vector text_uint16;\n std::vector text_uint32;\n std::vector 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":"#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}Made sure that the destruction of one window won't kill the rest#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":"\/*************************************************************************\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 \n#include \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 FunctorT;\n\n template \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& func,\n double nTimeout,\n char const* const ) :\n#else\n Delay( const boost::function0& 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 \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 \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 \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 \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 *\/\nINTEGRATION: 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.\/*************************************************************************\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 * \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 \n#include \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 FunctorT;\n\n template \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& func,\n double nTimeout,\n char const* const ) :\n#else\n Delay( const boost::function0& 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 \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 \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 \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 \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":"#include \"bilgamesh_internal.hh\"\n#include \n#include \n\ntemplate \n_bgm_action::_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 \n_bgm_action::_bgm_action (bool b, _bgm_move_capture mc, _bgm_piece_to_piece ptp, T s, T e, const std::vector& cm, const std::vector& 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 \n_bgm_action::operator bool() const\n{\n return 0 != start_;\n}\n\ntemplate \nbool\n_bgm_action::is_man_to_king () const\n{\n return _bgm_man_to_king == piece_to_piece;\n}\n\ntemplate \nbool\n_bgm_action::is_capture () const\n{\n return move_capture == _bgm_capture;\n}\n\ntemplate \nT\n_bgm_action::first () const\n{\n if (black_move) {\n return start_;\n } else {\n return 33 - start_;\n }\n}\n\ntemplate \nT\n_bgm_action::last () const\n{\n if (black_move) {\n return end_;\n } else {\n return 33 - end_;\n }\n}\n\ntemplate \n_bgm_action\n_bgm_action::clone () const\n{\n return _bgm_action(*this);\n}\n\ntemplate \n_bgm_action&\n_bgm_action::join (const _bgm_action& 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 \nvoid\n_bgm_action::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 \nvoid\n_bgm_action::get_all_hop_positions (std::vector& 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 \nstd::ostream&\noperator << (std::ostream& os, const _bgm_action& in)\n{\n os << in.first () << \"-\" << in.last ();\n return os;\n}\n\ntemplate class _bgm_action;\n\ntemplate std::ostream& operator << (std::ostream&, const _bgm_action&);\nAccount for white.#include \"bilgamesh_internal.hh\"\n#include \n#include \n\ntemplate \n_bgm_action::_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 \n_bgm_action::_bgm_action (bool b, _bgm_move_capture mc, _bgm_piece_to_piece ptp, T s, T e, const std::vector& cm, const std::vector& 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 \n_bgm_action::operator bool() const\n{\n return 0 != start_;\n}\n\ntemplate \nbool\n_bgm_action::is_man_to_king () const\n{\n return _bgm_man_to_king == piece_to_piece;\n}\n\ntemplate \nbool\n_bgm_action::is_capture () const\n{\n return move_capture == _bgm_capture;\n}\n\ntemplate \nT\n_bgm_action::first () const\n{\n if (black_move) {\n return start_;\n } else {\n return 33 - start_;\n }\n}\n\ntemplate \nT\n_bgm_action::last () const\n{\n if (black_move) {\n return end_;\n } else {\n return 33 - end_;\n }\n}\n\ntemplate \n_bgm_action\n_bgm_action::clone () const\n{\n return _bgm_action(*this);\n}\n\ntemplate \n_bgm_action&\n_bgm_action::join (const _bgm_action& 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 \nvoid\n_bgm_action::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 \nvoid\n_bgm_action::get_all_hop_positions (std::vector& 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 \nstd::ostream&\noperator << (std::ostream& os, const _bgm_action& in)\n{\n os << in.first () << \"-\" << in.last ();\n return os;\n}\n\ntemplate class _bgm_action;\n\ntemplate std::ostream& operator << (std::ostream&, const _bgm_action&);\n<|endoftext|>"} {"text":"#include \"hornet\/java.hh\"\n#include \"hornet\/vm.hh\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace hornet {\n\nclass_file::class_file(void *data, size_t size)\n : _offset(0)\n , _size(size)\n , _data(reinterpret_cast(data))\n{\n}\n\nclass_file::~class_file()\n{\n}\n\nstd::shared_ptr 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(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 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_count);\n\n for (auto idx = 0; idx < constant_pool_count-1; idx++) {\n auto tag = read_u1();\n std::shared_ptr 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 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 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 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 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 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 class_file::read_const_integer()\n{\n auto value = read_u4();\n \n return cp_info::make_integer(value);\n}\n\nstd::shared_ptr 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 class_file::read_const_long()\n{\n auto bytes = read_u8();\n\n return cp_info::make_long(bytes);\n}\n\nstd::shared_ptr 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 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 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 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(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 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 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 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();\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(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\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(new unknown_attr);\n}\n\nstd::unique_ptr\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(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(read_u1()) << 8\n | static_cast(read_u1());\n}\n\nuint32_t class_file::read_u4()\n{\n return static_cast(read_u1()) << 24\n | static_cast(read_u1()) << 16\n | static_cast(read_u1()) << 8\n | static_cast(read_u1());\n}\n\nuint64_t class_file::read_u8()\n{\n return static_cast(read_u4()) << 32 | read_u4();\n}\n\n}\njava\/class_file: Fix parse_type() for array types#include \"hornet\/java.hh\"\n#include \"hornet\/vm.hh\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace hornet {\n\nclass_file::class_file(void *data, size_t size)\n : _offset(0)\n , _size(size)\n , _data(reinterpret_cast(data))\n{\n}\n\nclass_file::~class_file()\n{\n}\n\nstd::shared_ptr 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(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 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_count);\n\n for (auto idx = 0; idx < constant_pool_count-1; idx++) {\n auto tag = read_u1();\n std::shared_ptr 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 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 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 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 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 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 class_file::read_const_integer()\n{\n auto value = read_u4();\n \n return cp_info::make_integer(value);\n}\n\nstd::shared_ptr 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 class_file::read_const_long()\n{\n auto bytes = read_u8();\n\n return cp_info::make_long(bytes);\n}\n\nstd::shared_ptr 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 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 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 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(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 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 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 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();\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(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\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(new unknown_attr);\n}\n\nstd::unique_ptr\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(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(read_u1()) << 8\n | static_cast(read_u1());\n}\n\nuint32_t class_file::read_u4()\n{\n return static_cast(read_u1()) << 24\n | static_cast(read_u1()) << 16\n | static_cast(read_u1()) << 8\n | static_cast(read_u1());\n}\n\nuint64_t class_file::read_u8()\n{\n return static_cast(read_u4()) << 32 | read_u4();\n}\n\n}\n<|endoftext|>"} {"text":"\/*\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 .\n *\/\n#include \n#include \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\nmove ripemd test into its own thing\/*\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 .\n *\/\n#include \n#include \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":"#include \n#include \n#include \n#include \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}\nTemplate up isRotation#include \n#include \n#include \n#include \n\nnamespace\n{\n template \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":"#include \n#include \n#include \n#include \n\n#include \"site.h\"\nusing namespace AhoViewer::Booru;\n\n#include \"settings.h\"\n\n#ifdef HAVE_LIBSECRET\n#include \n#endif \/\/ HAVE_LIBSECRET\n\n\/\/ 1: page, 2: limit, 3: tags\nconst std::map 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::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::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\n _shared_site(Ts&&...args) : Site(std::forward(args)...) { }\n};\n\nstd::shared_ptr 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& Site::get_missing_pixbuf()\n{\n static const Glib::RefPtr 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(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(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(userp)->m_MutexMap[data].lock();\n}\n\nvoid Site::share_unlock_cb(CURL*, curl_lock_data data, void *userp)\n{\n static_cast(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(ifs),\n std::istream_iterator(),\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 &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(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 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 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(ofs, \"\\n\"));\n}\nbooru\/site: Add comment about _shared_site#include \n#include \n#include \n#include \n\n#include \"site.h\"\nusing namespace AhoViewer::Booru;\n\n#include \"settings.h\"\n\n#ifdef HAVE_LIBSECRET\n#include \n#endif \/\/ HAVE_LIBSECRET\n\n\/\/ 1: page, 2: limit, 3: tags\nconst std::map 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::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::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\n _shared_site(Args&&... v) : Site(std::forward(v)...) { }\n};\n\nstd::shared_ptr 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& Site::get_missing_pixbuf()\n{\n static const Glib::RefPtr 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(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(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(userp)->m_MutexMap[data].lock();\n}\n\nvoid Site::share_unlock_cb(CURL*, curl_lock_data data, void *userp)\n{\n static_cast(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(ifs),\n std::istream_iterator(),\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 &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(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 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 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(ofs, \"\\n\"));\n}\n<|endoftext|>"} {"text":"\/\/ 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 \n\n#include \n#include \n#include \n\n#include \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=\", \"Use the 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=\", \"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 globalChainBaseParams;\n\nconst CBaseChainParams& BaseParams()\n{\n assert(globalChainBaseParams);\n return *globalChainBaseParams;\n}\n\nstd::unique_ptr CreateBaseChainParams(const std::string& chain)\n{\n if (chain == CBaseChainParams::MAIN)\n return MakeUnique(\"\", 8370);\n else if (chain == CBaseChainParams::TESTNET)\n return MakeUnique(\"testnet3\", 18370);\n else if (chain == CBaseChainParams::REGTEST)\n return MakeUnique(\"regtest\", 18470);\n else if (chain == CBaseChainParams::SIGNET) {\n return MakeUnique(\"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}\ncompile\/\/ 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 \n\n#include \n#include \n#include \n\n#include \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=\", \"Use the 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=\", \"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 globalChainBaseParams;\n\nconst CBaseChainParams& BaseParams()\n{\n assert(globalChainBaseParams);\n return *globalChainBaseParams;\n}\n\nstd::unique_ptr CreateBaseChainParams(const std::string& chain)\n{\n if (chain == CBaseChainParams::MAIN)\n return MakeUnique(\"\", 8370);\n else if (chain == CBaseChainParams::TESTNET)\n return MakeUnique(\"testnet3\", 18370);\n else if (chain == CBaseChainParams::REGTEST)\n return MakeUnique(\"regtest\", 18470);\n else if (chain == CBaseChainParams::SIGNET)\n return MakeUnique(\"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":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Copyright (c) Lewis Baker\n\/\/ Licenced under MIT license. See LICENSE.txt for details.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#include \n#include \n#include \n#include \n\n#include \n\n#include \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>\n\t{\n\t\tco_return std::make_unique(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\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\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\n\t{\n\t\tcounter temp;\n\n\t\t\/\/ Should be calling copy-constructor here since .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\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\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 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\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\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& 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\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::value,\n\t\t\t\t\"co_await r-value reference of lazy_task 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::value,\n\t\t\t\t\"co_await l-value reference of lazy_task 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}\nUndefine NDEBUG in test\/main.cpp so asserts are always enabled.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\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 \n#include \n#include \n#include \n\n#include \n\n#include \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>\n\t{\n\t\tco_return std::make_unique(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\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\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\n\t{\n\t\tcounter temp;\n\n\t\t\/\/ Should be calling copy-constructor here since .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\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\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 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\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\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& 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\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::value,\n\t\t\t\t\"co_await r-value reference of lazy_task 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::value,\n\t\t\t\t\"co_await l-value reference of lazy_task 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":"\/\/ 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 \n#include \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\nadd numinputplanes to DimFromArgs\/\/ 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 \n#include \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":"\/\/ ========================================================================== \/\/\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 \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 \n\n#include \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 indices;\n vector 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 nn_indices;\n vector 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 indices;\n vector 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 nn_indices;\n vector 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 > indices;\n vector > 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 > nn_indices;\n vector > 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 queries(num_queries);\n for (size_t i = 0; i != queries.size(); ++i)\n queries[i] = i;\n\n vector > indices;\n vector > 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 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 > nn_indices;\n vector > 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}Clean up unit tests.\/\/ ========================================================================== \/\/\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 \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 \n\n#include \n\n#include \n\n\nusing namespace DO;\nusing namespace std;\n\n\ninline vector range(int begin, int end)\n{\n vector _range(end-begin);\n for (int i = begin; i < end; ++i)\n _range[i-begin] = i;\n return _range;\n}\n\ninline vector range(int end)\n{\n return range(0, end);\n}\n\ntemplate \ninline set to_set(const vector& v)\n{\n return set(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 nn_indices;\n vector 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 nn_indices;\n vector 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 indices;\n vector 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 nn_indices;\n vector 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 > indices;\n vector > 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 > nn_indices;\n vector > 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 queries(num_queries);\n for (size_t i = 0; i != queries.size(); ++i)\n queries[i] = i;\n\n vector > indices;\n vector > 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 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 > nn_indices;\n vector > 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":"#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\"<Update ofApp.cpp#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\"<"} {"text":"#pragma once\n#ifndef SCOPEEXIT_HPP\n# define SCOPEEXIT_HPP\n\n#include \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 \nclass scope_exit\n{\npublic:\n explicit scope_exit(T&& f) noexcept : f_(::std::forward(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\ninline scope_exit make_scope_exit(T&& f)\n{\n return scope_exit(::std::forward(f));\n}\n\ntemplate\ninline scope_exit operator+(scope_exit_helper&&, T&& f)\n{\n return scope_exit(::std::forward(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\nsome fixes#pragma once\n#ifndef SCOPEEXIT_HPP\n# define SCOPEEXIT_HPP\n\n#include \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 \nclass scope_exit\n{\npublic:\n explicit scope_exit(T&& f) noexcept : f_(::std::forward(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\ninline scope_exit make_scope_exit(T&& f) noexcept\n{\n return scope_exit(::std::forward(f));\n}\n\ntemplate\ninline scope_exit operator+(scope_exit_helper&&, T&& f) noexcept\n{\n return scope_exit(::std::forward(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":"\/*\n**\n** Author(s):\n** - Pierre ROULLON \n**\n** Copyright (C) 2012, 2013 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \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(pObj));\n std::string propName = qi::jni::toString(name);\n\n qi::Future* ret = new qi::Future();\n\n qi::jni::JNIAttach attach(env);\n\n try\n {\n *ret = obj.property(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(pObj);\n std::string propName = qi::jni::toString(name);\n\n qi::jni::JNIAttach attach(env);\n\n auto value = qi::AnyValue::from(property);\n try\n {\n qi::Future propertyFuture = obj->setProperty(propName, std::move(value));\n qi::Future future = qi::toAnyValueFuture(std::move(propertyFuture));\n auto futurePtr = new qi::Future(std::move(future));\n return reinterpret_cast(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(pObject));\n std::string method;\n qi::Future* 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(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(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(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(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 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(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 ¶ms) -> 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::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 signalLinkFuture = anyObject->connect(signalName, subscriber);\n\n qi::Future future = qi::toAnyValueFuture(std::move(signalLinkFuture));\n auto futurePtr = new qi::Future(std::move(future));\n return reinterpret_cast(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(pObject);\n qi::Future disconnectFuture = anyObject->disconnect(subscriberId);\n\n qi::Future future = qi::toAnyValueFuture(std::move(disconnectFuture));\n auto futurePtr = new qi::Future(std::move(future));\n return reinterpret_cast(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(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}\nDelete signal parameter local reference\/*\n**\n** Author(s):\n** - Pierre ROULLON \n**\n** Copyright (C) 2012, 2013 Aldebaran Robotics\n** See COPYING for the license\n*\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \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(pObj));\n std::string propName = qi::jni::toString(name);\n\n qi::Future* ret = new qi::Future();\n\n qi::jni::JNIAttach attach(env);\n\n try\n {\n *ret = obj.property(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(pObj);\n std::string propName = qi::jni::toString(name);\n\n qi::jni::JNIAttach attach(env);\n\n auto value = qi::AnyValue::from(property);\n try\n {\n qi::Future propertyFuture = obj->setProperty(propName, std::move(value));\n qi::Future future = qi::toAnyValueFuture(std::move(propertyFuture));\n auto futurePtr = new qi::Future(std::move(future));\n return reinterpret_cast(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(pObject));\n std::string method;\n qi::Future* 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(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(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(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(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 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(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 ¶ms) -> 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::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 signalLinkFuture = anyObject->connect(signalName, subscriber);\n\n qi::Future future = qi::toAnyValueFuture(std::move(signalLinkFuture));\n auto futurePtr = new qi::Future(std::move(future));\n return reinterpret_cast(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(pObject);\n qi::Future disconnectFuture = anyObject->disconnect(subscriberId);\n\n qi::Future future = qi::toAnyValueFuture(std::move(disconnectFuture));\n auto futurePtr = new qi::Future(std::move(future));\n return reinterpret_cast(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(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":"#include \n\n#ifdef PLATFORM_POSIX\n#\tinclude \n#else\n#\twarning No regex support on nonposix systems!\n#endif\n\n#include \n#include \n#include \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\t\t\t\t\t\tRegexMatchVec;\n\n\ttypedef variant::type>\tReplacementEntry;\n\ttypedef std::vector\t\t\t\tReplacementEntryVec;\n\n\tclass ReplacementEntryVisitor : public static_visitor\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(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 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, ®ex, &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\n\t{\n\tpublic:\n\t\tImpl(const std::string& str) : BasicRegexImpl(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}\nadd \\w regex metacharacter support#include \n\n#ifdef PLATFORM_POSIX\n#\tinclude \n#else\n#\twarning No regex support on nonposix systems!\n#endif\n\n#include \n#include \n#include \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\t\t\t\t\t\tRegexMatchVec;\n\n\ttypedef variant::type>\tReplacementEntry;\n\ttypedef std::vector\t\t\t\tReplacementEntryVec;\n\n\tclass ReplacementEntryVisitor : public static_visitor\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(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 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, ®ex, &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\n\t{\n\tpublic:\n\t\tImpl(const std::string& str) : BasicRegexImpl(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":"\/\/ 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::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(node));\n } else {\n rassert(is_internal(node));\n return internal_node::is_underfull(sizer->block_size(), reinterpret_cast(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(node), reinterpret_cast(sibling));\n } else {\n rassert(is_internal(node));\n return internal_node::is_mergable(sizer->block_size(), reinterpret_cast(node), reinterpret_cast(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(node),\n reinterpret_cast(rnode), median);\n } else {\n internal_node::split(sizer->block_size(), reinterpret_cast(node),\n reinterpret_cast(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(node), reinterpret_cast(rnode));\n } else {\n internal_node::merge(sizer->block_size(), reinterpret_cast(node), reinterpret_cast(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(node));\n } else if (node->magic == internal_node_t::expected_magic) {\n internal_node::validate(sizer->block_size(), reinterpret_cast(node));\n } else {\n unreachable(\"Invalid leaf node type.\");\n }\n#endif\n}\n\n} \/\/ namespace node\nRemoved superfluous backslash\/\/ 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::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(node));\n } else {\n rassert(is_internal(node));\n return internal_node::is_underfull(sizer->block_size(), reinterpret_cast(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(node), reinterpret_cast(sibling));\n } else {\n rassert(is_internal(node));\n return internal_node::is_mergable(sizer->block_size(), reinterpret_cast(node), reinterpret_cast(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(node),\n reinterpret_cast(rnode), median);\n } else {\n internal_node::split(sizer->block_size(), reinterpret_cast(node),\n reinterpret_cast(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(node), reinterpret_cast(rnode));\n } else {\n internal_node::merge(sizer->block_size(), reinterpret_cast(node), reinterpret_cast(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(node));\n } else if (node->magic == internal_node_t::expected_magic) {\n internal_node::validate(sizer->block_size(), reinterpret_cast(node));\n } else {\n unreachable(\"Invalid leaf node type.\");\n }\n#endif\n}\n\n} \/\/ namespace node\n<|endoftext|>"} {"text":"#include \"mock_server.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\ntemplate \nMockServer::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 lock(mutex_);\n server_thread_ = std::thread(&MockServer::serverThread, this);\n\n cv_.wait(lock, [this] { return initialized_; });\n lock.unlock();\n spinOnce(); \/\/ spin to accept connections immediately\n}\n\ntemplate \nMockServer::~MockServer() {\n {\n std::lock_guard _(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 \nMockServer& MockServer::onReceiveRobotCommand(\n ReceiveRobotCommandCallbackT on_receive_robot_command) {\n std::lock_guard _(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 \nMockServer& MockServer::spinOnce() {\n std::unique_lock 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 \nvoid MockServer::serverThread() {\n std::unique_lock 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(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(size), rv) << \"Receive error on TCP socket\";\n };\n\n uint16_t udp_port;\n handleCommand(\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(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(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 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 \nMockServer& MockServer::generic(\n std::function::Socket&, MockServer::Socket&)> generic_command) {\n std::lock_guard _(mutex_);\n commands_.emplace(\"generic\", generic_command);\n return *this;\n}\n\ntemplate \nvoid MockServer::sendInitialState(Socket&) {}\n\ntemplate <>\nvoid MockServer::sendInitialState(Socket& udp_socket) {\n research_interface::robot::RobotState state{};\n state.message_id = ++sequence_number_;\n udp_socket.sendBytes(&state, sizeof(state));\n}\nMockServer: Only send initial state for Robot.#include \"mock_server.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\ntemplate \nMockServer::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 lock(mutex_);\n server_thread_ = std::thread(&MockServer::serverThread, this);\n\n cv_.wait(lock, [this] { return initialized_; });\n lock.unlock();\n spinOnce(); \/\/ spin to accept connections immediately\n}\n\ntemplate \nMockServer::~MockServer() {\n {\n std::lock_guard _(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 \nMockServer& MockServer::onReceiveRobotCommand(\n ReceiveRobotCommandCallbackT on_receive_robot_command) {\n std::lock_guard _(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 \nMockServer& MockServer::spinOnce() {\n std::unique_lock 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 \nvoid MockServer::serverThread() {\n std::unique_lock 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(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(size), rv) << \"Receive error on TCP socket\";\n };\n\n uint16_t udp_port;\n handleCommand(\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(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(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 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 \nMockServer& MockServer::generic(\n std::function::Socket&, MockServer::Socket&)> generic_command) {\n std::lock_guard _(mutex_);\n commands_.emplace(\"generic\", generic_command);\n return *this;\n}\n\ntemplate \nvoid MockServer::sendInitialState(Socket&) {}\n\ntemplate <>\nvoid MockServer::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":"\/*\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** .\n*\/\n\n#include \n#include \n#include \n#include \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 hosts;\n std::list 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::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}\nNotification: better unit test.\/*\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** .\n*\/\n\n#include \n#include \n#include \n#include \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 hosts;\n std::list 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::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":"\/*\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 \n#include \n#include \n#ifdef _WINDOWS\n#include \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 \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\n{\npublic:\n\n CImgDenoisePlugin(OfxImageEffectHandle handle)\n : CImgFilterPluginHelper(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& 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}\nCImgNoise: bug fix\/*\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 \n#include \n#include \n#ifdef _WINDOWS\n#include \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 \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\n{\npublic:\n\n CImgDenoisePlugin(OfxImageEffectHandle handle)\n : CImgFilterPluginHelper(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& 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":"\/\/ -*- 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 \n#include \n\n#ifdef BALL_HAS_GLEW\n#\tinclude \n#endif\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"mainframe.h\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#ifdef Q_WS_X11\n#include \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}\nFirst Usage of UIOperationMode: cancel User menu in Kiosk mode\/\/ -*- 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 \n#include \n\n#ifdef BALL_HAS_GLEW\n#\tinclude \n#endif\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"mainframe.h\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#ifdef Q_WS_X11\n#include \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":"\/*\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}\npartially reverting commit 33abe65 to address SyncDriver issues #53\/*\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":"\/\/ 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 \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 \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& staticVars){\n\tCompiler compiler(runtime.getLogger());\n\tstd::vector 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& staticVars) {\n\tconst StringData file = IO::loadFile(filename);\n\treturn _eval(runtime,CodeFragment(StringId(filename),file),staticVars);\n}\n\n\/\/! (static)\nstd::pair loadAndExecute(Runtime & runtime, const std::string & filename) {\n\tconst std::unordered_map staticVars;\n\treturn loadAndExecute(runtime,filename,staticVars);\n}\n\nstd::pair loadAndExecute(Runtime & runtime, const std::string & filename,const std::unordered_map& 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 eval(Runtime & runtime, const StringData & code,const StringId & fileId) {\n\ttry {\n\t\tstd::unordered_map 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 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}\nCompile fix for empty unordered_map and clang\/\/ 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 \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 \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& staticVars){\n\tCompiler compiler(runtime.getLogger());\n\tstd::vector 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& staticVars) {\n\tconst StringData file = IO::loadFile(filename);\n\treturn _eval(runtime,CodeFragment(StringId(filename),file),staticVars);\n}\n\n\/\/! (static)\nstd::pair loadAndExecute(Runtime & runtime, const std::string & filename) {\n\treturn loadAndExecute(runtime, filename, {});\n}\n\nstd::pair loadAndExecute(Runtime & runtime, const std::string & filename,const std::unordered_map& 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 eval(Runtime & runtime, const StringData & code,const StringId & fileId) {\n\ttry {\n\t\tstd::unordered_map 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 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":"#define BOOST_TEST_MODULE OctreeTest\n\n#include \n\n#include \n\n#include \"octree.h\"\n#include \"tensor.h\"\n\nusing namespace nbody;\n\nstruct Leaf;\nstruct Node;\n\nusing TestOctree = Octree;\nusing TestQuadtree = Octree;\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\nAdded a method for verifying the structure of an octree#define BOOST_TEST_MODULE OctreeTest\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"octree.h\"\n#include \"tensor.h\"\n\nusing namespace nbody;\n\nstruct Leaf;\nstruct Node;\n\nusing TestOctree = Octree;\nusing TestQuadtree = Octree;\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\nCheckOctreeResult checkOctree(\n\t\tOctree const& octree,\n\t\tstd::vector > > allLeafPairs) {\n\t\/\/ Create a stack storing the points that belong to the current node.\n\tstd::vector > > > 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 > > 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 > > 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 > 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 > > 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":"\/\/ -*- 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 \n#include \n\n#ifdef BALL_HAS_GLEW\n#\tinclude \n#endif\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"mainframe.h\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#ifdef Q_WS_X11\n#include \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}\nLanguage support : correct formatting\/\/ -*- 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 \n#include \n\n#ifdef BALL_HAS_GLEW\n#\tinclude \n#endif\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"mainframe.h\"\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#ifdef Q_WS_X11\n#include \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":"#include \n\n#include \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}\nFix failing tests#include \n\n#include \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":"#include \"gigasecond.h\"\n#define BOOST_TEST_MAIN\n#include \n\n\/\/ See \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\nincluding neded boost posix_time (#201)#include \"gigasecond.h\"\n#define BOOST_TEST_MAIN\n#include \n#include \"boost\/date_time\/posix_time\/posix_time.hpp\"\n\n\/\/ See \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":"\/\/ -*- 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 \n#include \n#include \n\nusing namespace std;\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\nColorProcessor::ColorProcessor()\n\tthrow()\n\t:\tUnaryProcessor()\n{\n\tclear();\n}\n\nColorProcessor::ColorProcessor(const ColorProcessor& color_Processor)\n\tthrow()\n\t:\tUnaryProcessor(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() << 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(*object))\n\t{\n\t\tobject->setColor(getColor(object->getComposite())); \n\t\treturn Processor::CONTINUE;\n\t}\n\n\tif (RTTI::isKindOf(*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\nfixed problem with cast in operator ()\/\/ -*- 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 \n#include \n#include \n\nusing namespace std;\n\nnamespace BALL\n{\n\tnamespace VIEW\n\t{\n\nColorProcessor::ColorProcessor()\n\tthrow()\n\t:\tUnaryProcessor()\n{\n\tclear();\n}\n\nColorProcessor::ColorProcessor(const ColorProcessor& color_Processor)\n\tthrow()\n\t:\tUnaryProcessor(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() << 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(*object))\n\t\t{\n\t\t\tColorExtension2* two_colored = dynamic_cast(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(*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(object);\n\tif (RTTI::isKindOf(*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":"Adicionado exercício 1069<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2009 Gael Guennebaud \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 .\n\n#include \"main.h\"\n\ntemplate 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::Real RealScalar;\n\n int rows = m.rows();\n int cols = m.cols();\n\n Scalar big = ei_random() * std::numeric_limits::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(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()) );\n CALL_SUBTEST( stable_norm(Vector4d()) );\n CALL_SUBTEST( stable_norm(VectorXd(ei_random(10,2000))) );\n CALL_SUBTEST( stable_norm(VectorXf(ei_random(10,2000))) );\n CALL_SUBTEST( stable_norm(VectorXcd(ei_random(10,2000))) );\n }\n}\n\nAdded missing casts.\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2009 Gael Guennebaud \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 .\n\n#include \"main.h\"\n\ntemplate 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::Real RealScalar;\n\n int rows = m.rows();\n int cols = m.cols();\n\n Scalar big = ei_random() * std::numeric_limits::max() * RealScalar(1e-4);\n Scalar small = static_cast(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(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(m.size());\n\n \/\/ test overflow\n VERIFY_IS_NOT_APPROX(static_cast(vbig.norm()), ei_sqrt(size)*big); \/\/ here the default norm must fail\n VERIFY_IS_APPROX(static_cast(vbig.stableNorm()), ei_sqrt(size)*big);\n VERIFY_IS_APPROX(static_cast(vbig.blueNorm()), ei_sqrt(size)*big);\n VERIFY_IS_APPROX(static_cast(vbig.hypotNorm()), ei_sqrt(size)*big);\n\n \/\/ test underflow\n VERIFY_IS_NOT_APPROX(static_cast(vsmall.norm()), ei_sqrt(size)*small); \/\/ here the default norm must fail\n VERIFY_IS_APPROX(static_cast(vsmall.stableNorm()), ei_sqrt(size)*small);\n VERIFY_IS_APPROX(static_cast(vsmall.blueNorm()), ei_sqrt(size)*small);\n VERIFY_IS_APPROX(static_cast(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()) );\n CALL_SUBTEST( stable_norm(Vector4d()) );\n CALL_SUBTEST( stable_norm(VectorXd(ei_random(10,2000))) );\n CALL_SUBTEST( stable_norm(VectorXf(ei_random(10,2000))) );\n CALL_SUBTEST( stable_norm(VectorXcd(ei_random(10,2000))) );\n }\n}\n<|endoftext|>"} {"text":"\/* 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 .\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 \n#include \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& 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& 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;\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 \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 MutableQueue;\n MutableQueue Q(&costs[0], &index_in_heap_map[0], compare);\n\n boost::detail::astar_bfs_visitor, 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\nRevert \"[Kraken] Fix A* heuristic cost\"\/* 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 .\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 \n#include \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& 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& 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;\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 \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 MutableQueue;\n MutableQueue Q(&costs[0], &index_in_heap_map[0], compare);\n\n boost::detail::astar_bfs_visitor, 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":"\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \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> 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 : std::set>(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(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 Program::shaders() const\n{\n\tstd::set shaders;\n for (ref_ptr 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(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 Program::getAttributeLocations(const std::vector & names) const\n{\n std::vector locations(names.size());\n for (unsigned i = 0; i Program::getUniformLocations(const std::vector & names) const\n{\n std::vector locations(names.size());\n for (unsigned i = 0; i Program::getResource(gl::GLenum programInterface, gl::GLuint index, const std::vector & props, gl::GLsizei * length)\n{\n std::vector 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 & 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 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(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 Program::getActiveUniforms(const std::vector & uniformIndices, const GLenum pname) const\n{\n std::vector result(uniformIndices.size());\n getActiveUniforms(static_cast(uniformIndices.size()), uniformIndices.data(), pname, result.data());\n return result;\n}\n\nstd::vector Program::getActiveUniforms(const std::vector & uniformIndices, const GLenum pname) const\n{\n std::vector indices(uniformIndices.size());\n for (unsigned i=0; i(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 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& 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> uniformPair : m_uniforms)\n\t\tuniformPair.second->update(this);\n}\n\nvoid Program::updateUniformBlockBindings() const\n{\n for (std::pair 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 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\nProgram::getResourceName(): Early out if nameLength == 0, #267\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \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> 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 : std::set>(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(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 Program::shaders() const\n{\n\tstd::set shaders;\n for (ref_ptr 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(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 Program::getAttributeLocations(const std::vector & names) const\n{\n std::vector locations(names.size());\n for (unsigned i = 0; i Program::getUniformLocations(const std::vector & names) const\n{\n std::vector locations(names.size());\n for (unsigned i = 0; i Program::getResource(gl::GLenum programInterface, gl::GLuint index, const std::vector & props, gl::GLsizei * length)\n{\n std::vector 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 & 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 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(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 Program::getActiveUniforms(const std::vector & uniformIndices, const GLenum pname) const\n{\n std::vector result(uniformIndices.size());\n getActiveUniforms(static_cast(uniformIndices.size()), uniformIndices.data(), pname, result.data());\n return result;\n}\n\nstd::vector Program::getActiveUniforms(const std::vector & uniformIndices, const GLenum pname) const\n{\n std::vector indices(uniformIndices.size());\n for (unsigned i=0; i(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 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& 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> uniformPair : m_uniforms)\n\t\tuniformPair.second->update(this);\n}\n\nvoid Program::updateUniformBlockBindings() const\n{\n for (std::pair 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 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":"#ifndef PLATE2D_HPP\n#define PLATE2D_HPP\n#include \n#ifndef WX_PRECOMP\n #include \n#endif\n#include \n\n#include \n#include \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& _objects, std::shared_ptr _model, std::shared_ptr _config, std::shared_ptr _settings);\n\n\n\/\/ std::function<> on_select_object {};\nprivate:\n std::vector& objects; \/\/< reference to parent vector\n std::shared_ptr model;\n std::shared_ptr config;\n std::shared_ptr 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 scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale);\n std::vector 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 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\nMake update_bed_size() public.#ifndef PLATE2D_HPP\n#define PLATE2D_HPP\n#include \n#ifndef WX_PRECOMP\n #include \n#endif\n#include \n\n#include \n#include \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& _objects, std::shared_ptr _model, std::shared_ptr _config, std::shared_ptr _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& objects; \/\/< reference to parent vector\n std::shared_ptr model;\n std::shared_ptr config;\n std::shared_ptr 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 scaled_points_to_pixel(const Slic3r::Polygon& poly, bool unscale);\n std::vector 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 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":"\/*\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}\nAdded last (?) suppressions for known issues.\/*\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":"\/**\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 \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 \/\/ !DEBUGBarrier check correct delete\/**\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 \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":"#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef unsigned char uchar;\n\ntemplate\nvoid readTests(const std::string &FileName, std::vector &inputDims,\n std::vector> &testInputs,\n std::vector> &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> temp;\n inputDims.push_back(temp);\n }\n\n unsigned testCount;\n testFile >> testCount;\n testOutputs.resize(testCount);\n\n vector testSizes(testCount);\n for(unsigned i = 0; i < testCount; i++) {\n testFile >> testSizes[i];\n }\n\n testInputs.resize(inputCount,vector(0));\n for(unsigned k=0; k> tmp;\n testInputs[k][i] = tmp;\n }\n }\n\n testOutputs.resize(testCount, vector(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}\nAdded readImageTests and compareArraysRMSD helpers for unit tests#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ntypedef unsigned char uchar;\n\ntemplate\nvoid readTests(const std::string &FileName, std::vector &inputDims,\n std::vector> &testInputs,\n std::vector> &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> temp;\n inputDims.push_back(temp);\n }\n\n unsigned testCount;\n testFile >> testCount;\n testOutputs.resize(testCount);\n\n vector testSizes(testCount);\n for(unsigned i = 0; i < testCount; i++) {\n testFile >> testSizes[i];\n }\n\n testInputs.resize(inputCount,vector(0));\n for(unsigned k=0; k> tmp;\n testInputs[k][i] = tmp;\n }\n }\n\n testOutputs.resize(testCount, vector(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 &pInputDims,\n std::vector &pTestInputs,\n std::vector &pTestOutSizes,\n std::vector &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> 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\nbool compareArraysRMSD(dim_type data_size, T *gold, T *data, float tolerance)\n{\n float accum = 0.0f;\n T minion = std::numeric_limits::lowest();\n T maxion = std::numeric_limits::max();\n for(dim_type i=0;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":"\/*\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))\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))\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))\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))\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\nCheck Size: Removed DatabaseCount, DatabaseQueue and DatabasesLRU\/*\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))\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))\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))\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))\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":"\/***************************************************************************\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 \r\n *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \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\nIgnore O_BINARY on non-Windows platforms.\/***************************************************************************\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 \r\n *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \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":"\/*\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 \n#endif\n#ifdef _MSC_VER\n#include \/\/ 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(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(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\nclangcl 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\/*\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 \n#endif\n#ifdef _MSC_VER\n#include \/\/ 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(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(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":"\/*=========================================================================\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; iGetPlane(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\nENH: Merge changes from main tree into VTK-5-0 branch. (cvs -q up -j1.5 -j1.6 Filtering\/vtkAbstractMapper.cxx)\/*=========================================================================\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; iGetPlane(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":"\/*************************************************************************\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\nINTEGRATION: CWS ooo19126 (1.2.504); FILE MERGED 2005\/09\/05 12:59:02 rt 1.2.504.1: #i54170# Change license header: remove SISSL\/*************************************************************************\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":"\/* 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 \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\nWhen reading ROT from KVStore the return ROT key size was ignored\/* 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 \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":"Clean up a little.<|endoftext|>"} {"text":"\/*\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 .\n *\/\n\n#pragma once\n\n#include \n#include \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(in) & 1) && size >= 1) {\n process(*in);\n ++in;\n --size;\n }\n if ((reinterpret_cast(in) & 3) && size >= 2) {\n process(*reinterpret_cast(in));\n in += 2;\n size -= 2;\n }\n if ((reinterpret_cast(in) & 7) && size >= 4) {\n process(*reinterpret_cast(in));\n in += 4;\n size -= 4;\n }\n \/\/ FIXME: do in three parallel loops\n while (size >= 8) {\n process(*reinterpret_cast(in));\n in += 8;\n size -= 8;\n }\n if (size >= 4) {\n process(*reinterpret_cast(in));\n in += 4;\n size -= 4;\n }\n if (size >= 2) {\n process(*reinterpret_cast(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}\nutils\/crc: use zlib for crc32 on non-x86 platforms\/*\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 .\n *\/\n\n#pragma once\n\n#include \n\n#if defined(__x86_64__) || defined(__i386__)\n#include \n#else\n#include \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(in) & 1) && size >= 1) {\n process(*in);\n ++in;\n --size;\n }\n if ((reinterpret_cast(in) & 3) && size >= 2) {\n process(*reinterpret_cast(in));\n in += 2;\n size -= 2;\n }\n if ((reinterpret_cast(in) & 7) && size >= 4) {\n process(*reinterpret_cast(in));\n in += 4;\n size -= 4;\n }\n \/\/ FIXME: do in three parallel loops\n while (size >= 8) {\n process(*reinterpret_cast(in));\n in += 8;\n size -= 8;\n }\n if (size >= 4) {\n process(*reinterpret_cast(in));\n in += 4;\n size -= 4;\n }\n if (size >= 2) {\n process(*reinterpret_cast(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 \n void process(T in) {\n static_assert(std::is_integral::value, \"T must be integral type.\");\n _r = ::crc32(_r, reinterpret_cast(&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":"\/*\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 \n\n#include \"webrtc\/rtc_base\/checks.h\"\n#include \"webrtc\/rtc_base\/macutils.h\"\n\nstatic_assert(\n static_cast(kCGNullWindowID) == webrtc::kNullWindowId,\n \"kNullWindowId needs to equal to kCGNullWindowID.\");\n\nnamespace webrtc {\n\nbool GetWindowList(rtc::FunctionView 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(\n CFArrayGetValueAtIndex(window_array, i));\n if (!window) {\n continue;\n }\n\n CFStringRef window_title = reinterpret_cast(\n CFDictionaryGetValue(window, kCGWindowName));\n if (!window_title) {\n continue;\n }\n\n CFNumberRef window_id = reinterpret_cast(\n CFDictionaryGetValue(window, kCGWindowNumber));\n if (!window_id) {\n continue;\n }\n\n CFNumberRef window_layer = reinterpret_cast(\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(\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(\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(&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(\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(\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(\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(\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\nCheck whether on_screen is null before performing CFBooleanGetValue()\/*\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 \n\n#include \"webrtc\/rtc_base\/checks.h\"\n#include \"webrtc\/rtc_base\/macutils.h\"\n\nstatic_assert(\n static_cast(kCGNullWindowID) == webrtc::kNullWindowId,\n \"kNullWindowId needs to equal to kCGNullWindowID.\");\n\nnamespace webrtc {\n\nbool GetWindowList(rtc::FunctionView 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(\n CFArrayGetValueAtIndex(window_array, i));\n if (!window) {\n continue;\n }\n\n CFStringRef window_title = reinterpret_cast(\n CFDictionaryGetValue(window, kCGWindowName));\n if (!window_title) {\n continue;\n }\n\n CFNumberRef window_id = reinterpret_cast(\n CFDictionaryGetValue(window, kCGWindowNumber));\n if (!window_id) {\n continue;\n }\n\n CFNumberRef window_layer = reinterpret_cast(\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(\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(\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(&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(\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(\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(\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(\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":"\/*************************************************************************\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 \n#endif\n\n#ifndef _EEITEM_HXX\n#include \n#endif\n#ifndef _EDITOBJ_HXX\n#include \n#endif\n#define ITEMID_FONTHEIGHT EE_CHAR_FONTHEIGHT\n#ifndef _SVX_FHGTITEM_HXX\n#include \n#endif\n#define ITEMID_FONT EE_CHAR_FONTHEIGHT\n#ifndef _SVX_FONTITEM_HXX\n#include \n#endif\n#define ITEMID_LANGUAGE EE_CHAR_LANGUAGE\n#ifndef _SVX_LANGITEM_HXX\n#include \n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n#ifndef _VCL_MAPUNIT_HXX\n#include \n#endif\n#ifndef _SV_MAPMOD_HXX\n#include \n#endif\n#ifndef _SV_OUTDEV_HXX\n#include \n#endif\n\n#ifndef _SVTOOLS_LINGUCFG_HXX_\n#include \n#endif\n#ifndef _UNDO_HXX\n#include \n#endif\n\n\n#include \n#include \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\nINTEGRATION: 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\/*************************************************************************\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 \n#endif\n\n#ifndef _EEITEM_HXX\n#include \n#endif\n#ifndef _EDITOBJ_HXX\n#include \n#endif\n#define ITEMID_FONTHEIGHT EE_CHAR_FONTHEIGHT\n#ifndef _SVX_FHGTITEM_HXX\n#include \n#endif\n#define ITEMID_FONT EE_CHAR_FONTHEIGHT\n#ifndef _SVX_FONTITEM_HXX\n#include \n#endif\n#define ITEMID_LANGUAGE EE_CHAR_LANGUAGE\n#ifndef _SVX_LANGITEM_HXX\n#include \n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n#ifndef _VCL_MAPUNIT_HXX\n#include \n#endif\n#ifndef _SV_MAPMOD_HXX\n#include \n#endif\n#ifndef _SV_OUTDEV_HXX\n#include \n#endif\n\n#ifndef _SVTOOLS_LINGUCFG_HXX_\n#include \n#endif\n#ifndef _UNDO_HXX\n#include \n#endif\n#ifndef _VOS_MUTEX_HXX_\n#include \n#endif\n\n#include \n#include \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":"\/*******************************************************************\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 \n#include \n#include \n#include \n\n#include \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}\ns\/iostream.h\/iostream\/g\/*******************************************************************\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 \n#include \n#include \n#include \n\n#include \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":"\/*=========================================================================\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 IDSetType;\n typedef vtkstd::vector 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}\nBUG: Fix surface selection\/*=========================================================================\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 IDSetType;\n typedef vtkstd::vector 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":"\/*************************************************************************\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 \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 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 curProfileDir;\n PRBool exists = PR_FALSE;\n nsCOMPtr 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 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\nmozilla registry.dat parsing\/*************************************************************************\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 \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 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 curProfileDir;\n PRBool exists = PR_FALSE;\n nsCOMPtr 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 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":"\/* 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_ *\/\nPetty trailing 0 fix\/* 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":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ oxygen.cpp\n\/\/ -------------------\n\/\/\n\/\/ Copyright (c) 2009 Hugo Pereira Da Costa \n\/\/ Copyright (c) 2006, 2007 Riccardo Iaconelli \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 \n#include \n#include \n#include \n#include \n#include \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}\nfixed applying style opacity to exceptions.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ oxygen.cpp\n\/\/ -------------------\n\/\/\n\/\/ Copyright (c) 2009 Hugo Pereira Da Costa \n\/\/ Copyright (c) 2006, 2007 Riccardo Iaconelli \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 \n#include \n#include \n#include \n#include \n#include \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":"\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999 Stefan Seefeld \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 \n#include \n#include \n#include \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}\nfiat lux...\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999 Stefan Seefeld \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 \n#include \n#include \n#include \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":"\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999,2000 Tobias Hunger \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}\nfix to make it compilable with gcc 2.95.2\/*$Id$\n *\n * This source file is a part of the Berlin Project.\n * Copyright (C) 1999,2000 Tobias Hunger \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":"\/* This file is part of the KDE project\n Copyright (C) 2001 Christoph Cullmann \n Copyright (C) 2001 Joseph Wenninger \n Copyright (C) 2001 Anders Lund \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 \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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}\nno logging stuff used here\/* This file is part of the KDE project\n Copyright (C) 2001 Christoph Cullmann \n Copyright (C) 2001 Joseph Wenninger \n Copyright (C) 2001 Anders Lund \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 \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \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":"ZMQhistSource: pack histos in AliHLTObjArray<|endoftext|>"} {"text":"\/**\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 \n#endif\n#include \n#include \n#include \n#include \n\n#include \n\n#ifdef __linux__\n#include \n#endif\n\n#include \n#ifdef __APPLE__\n#include \n#include \n#endif\n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \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 download(const std::string& url, const std::string& path)\n{\n Try 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::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 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 > 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 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(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(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 netmask() const { return netmask_; }\n\n \/\/ Returns the prefix of the subnet defined by the net mask.\n Option 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(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 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(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__\nAdjusted the includes in stout\/net.hpp to avoid definition conflicts caused by netlink.\/**\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF 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 \n#endif\n#include \n#include \n#include \n#include \n\n#include \n\n#ifdef __linux__\n#include \n#include \n#endif\n\n#ifdef __APPLE__\n#include \n#include \n#include \n#endif\n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \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 download(const std::string& url, const std::string& path)\n{\n Try 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::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 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 > 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 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(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(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 netmask() const { return netmask_; }\n\n \/\/ Returns the prefix of the subnet defined by the net mask.\n Option 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(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 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(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":"\/*\n * MediaPlayer.cpp\n *\n * Created on: 2016年12月5日\n * Author: xzl\n *\/\n\n#include \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关闭log\/*\n * MediaPlayer.cpp\n *\n * Created on: 2016年12月5日\n * Author: xzl\n *\/\n\n#include \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":"#include \"Players\/Genetic_AI.h\"\n\n#include \n#include \n#include \n#include \n#include \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}\nSimpler iterator math in principal variation review#include \"Players\/Genetic_AI.h\"\n\n#include \n#include \n#include \n#include \n#include \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":"#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(\"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(\"Conversion canceled.<\/b>\");\n utils.killed = false;\n return;\n }\n if (code != 0) {\n utils.addToLog(\"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(\"Conversion complete.<\/b>\");\n utils.addToLog(\"Saved to: \" + utils.getCurrentFilename());\n}\nfixed conversion progress bar issue on windows#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(\"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(\"Conversion canceled.<\/b>\");\n utils.killed = false;\n return;\n }\n if (code != 0) {\n utils.addToLog(\"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(\"Conversion complete.<\/b>\");\n utils.addToLog(\"Saved to: \" + utils.getCurrentFilename());\n}\n<|endoftext|>"} {"text":"#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 \n#include \n#include \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(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(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(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(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(\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(\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& 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(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\nData: Add functions for dealing with path names#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 \n#include \n#include \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(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(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(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(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(\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(\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& 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(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":"\/\/ 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;\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\nRm duplicated SMDS_MeshElement::setVtkId(int vtkId)\/\/ 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;\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":"\/*=========================================================================\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 \n\n#include \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; iGetIndexToObjectTransform() )\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 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(\n tube->GetPoint( k ) );\n OutputImage->TransformPhysicalPointToContinuousIndex(\n\ttubeIndexPhysTransform->TransformPoint( tubePoint->GetPosition() ),\n\tpoint );\n for( unsigned int i=0; iGetLargestPossibleRegion().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;tpindSetPixel( 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(\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 )\nAdd TODO\/*=========================================================================\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 \n\n#include \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; iGetIndexToObjectTransform() )\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 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(\n tube->GetPoint( k ) );\n OutputImage->TransformPhysicalPointToContinuousIndex(\n\ttubeIndexPhysTransform->TransformPoint( tubePoint->GetPosition() ),\n\tpoint );\n for( unsigned int i=0; iGetLargestPossibleRegion().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;tpindSetPixel( 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(\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":"#include \"ScaledImageFactory.h\"\r\n\r\n#include \r\n\r\n#include \r\n\r\n#define STB_IMAGE_RESIZE_IMPLEMENTATION\r\n#include \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}Fix C4239 warning#include \"ScaledImageFactory.h\"\r\n\r\n#include \r\n\r\n#include \r\n\r\n#define STB_IMAGE_RESIZE_IMPLEMENTATION\r\n#include \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":"Abstract Classes - Polymorphism<|endoftext|>"} {"text":"Fix creation of function definition asts<|endoftext|>"} {"text":"\/*************************************************************************************\n * Copyright (C) 2012 by Alejandro Fiestas Olivares *\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 \n#include \n#include \n\n#include \n#include \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 embeddedModeSize;\n Q_FOREACH(KScreen::Mode* mode, embeddedModes) {\n embeddedModeSize.insert(mode->id(), mode->size());\n }\n\n QList 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 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\"\nUse better variable names in Generator::biggestOutput()\/*************************************************************************************\n * Copyright (C) 2012 by Alejandro Fiestas Olivares *\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 \n#include \n#include \n\n#include \n#include \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 embeddedModeSize;\n Q_FOREACH(KScreen::Mode* mode, embeddedModes) {\n embeddedModeSize.insert(mode->id(), mode->size());\n }\n\n QList 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 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":"\/*\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\nbugfix: result.bars[1] may be used uninitialized\/*\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":"\/**\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 \n#include \"..\/JPetCommonTools\/JPetCommonTools.h\"\n#include \"..\/JPetLoggerInclude.h\"\n#include \"..\/JPetScopeConfigParser\/JPetScopeConfigParser.h\"\n#include \n\n\nJPetCmdParser::JPetCmdParser(): fOptionsDescriptions(\"Allowed options\")\n{\n fOptionsDescriptions.add_options()\n (\"help,h\", \"Displays this help message.\")\n (\"type,t\", po::value()->required()->implicit_value(\"\"), \"Type of file: hld, zip, root or scope.\")\n (\"file,f\", po::value< std::vector >()->required()->multitoken(), \"File(s) to open.\")\n (\"outputPath,o\", po::value(), \"Location to which the outputFiles will be saved.\")\n (\"range,r\", po::value< std::vector >()->multitoken()->default_value({ -1, -1}, \"\"), \"Range of events to process e.g. -r 1 1000 .\")\n (\"param,p\", po::value(), \"xml file with TRB settings used by the unpacker program.\")\n (\"runId,i\", po::value(), \"Run id.\")\n (\"progressBar,b\", \"Progress bar.\")\n (\"localDB,l\", po::value(), \"The file to use as the parameter database.\")\n (\"localDBCreate,L\", po::value(), \"File name to which the parameter database will be saved.\");\n}\n\nJPetCmdParser::~JPetCmdParser()\n{\n \/**\/\n}\n\nstd::vector 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 >().size() != 2) {\n ERROR(\"Wrong number of bounds in range.\");\n std::cerr << \"Wrong number of bounds in range: \" << variablesMap[\"range\"].as< std::vector >().size() << std::endl;\n return false;\n }\n if (\n variablesMap[\"range\"].as< std::vector >()[0]\n > variablesMap[\"range\"].as< std::vector >()[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();\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();\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 fileNames(variablesMap[\"file\"].as< std::vector >());\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 JPetCmdParser::generateOptions(const po::variables_map& optsMap) const\n{\n std::map 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 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 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__ *\/\nAdded zip phrase to function in JPetCmdParser\/**\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 \n#include \"..\/JPetCommonTools\/JPetCommonTools.h\"\n#include \"..\/JPetLoggerInclude.h\"\n#include \"..\/JPetScopeConfigParser\/JPetScopeConfigParser.h\"\n#include \n\n\nJPetCmdParser::JPetCmdParser(): fOptionsDescriptions(\"Allowed options\")\n{\n fOptionsDescriptions.add_options()\n (\"help,h\", \"Displays this help message.\")\n (\"type,t\", po::value()->required()->implicit_value(\"\"), \"Type of file: hld, zip, root or scope.\")\n (\"file,f\", po::value< std::vector >()->required()->multitoken(), \"File(s) to open.\")\n (\"outputPath,o\", po::value(), \"Location to which the outputFiles will be saved.\")\n (\"range,r\", po::value< std::vector >()->multitoken()->default_value({ -1, -1}, \"\"), \"Range of events to process e.g. -r 1 1000 .\")\n (\"param,p\", po::value(), \"xml file with TRB settings used by the unpacker program.\")\n (\"runId,i\", po::value(), \"Run id.\")\n (\"progressBar,b\", \"Progress bar.\")\n (\"localDB,l\", po::value(), \"The file to use as the parameter database.\")\n (\"localDBCreate,L\", po::value(), \"File name to which the parameter database will be saved.\");\n}\n\nJPetCmdParser::~JPetCmdParser()\n{\n \/**\/\n}\n\nstd::vector 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 >().size() != 2) {\n ERROR(\"Wrong number of bounds in range.\");\n std::cerr << \"Wrong number of bounds in range: \" << variablesMap[\"range\"].as< std::vector >().size() << std::endl;\n return false;\n }\n if (\n variablesMap[\"range\"].as< std::vector >()[0]\n > variablesMap[\"range\"].as< std::vector >()[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();\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();\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 fileNames(variablesMap[\"file\"].as< std::vector >());\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 JPetCmdParser::generateOptions(const po::variables_map& optsMap) const\n{\n std::map 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 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 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":"#include \"ui_mainwindow.h\"\n#include \"converter.h\"\n#include \"utilities.h\"\n#include \"window.h\"\n#include \n\nConverter::Converter(QObject *parent) : QObject(parent) {\n}\n\nvoid Converter::start() {\n utils.addToLog(\"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(\"Conversion canceled.<\/b>\");\n utils.killed = false;\n win.toggleConversionButton();\n return;\n }\n if (code != 0) {\n utils.addToLog(\"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(\"Conversion complete.<\/b>\");\n utils.addToLog(\"Saved to: \" + utils.getCurrentFilename());\n\n if (win.ui->menuShowFile->isChecked())\n utils.showFileInDirectory();\n}\nbitrate calculating incldudes audio settings#include \"ui_mainwindow.h\"\n#include \"converter.h\"\n#include \"utilities.h\"\n#include \"window.h\"\n#include \n\nConverter::Converter(QObject *parent) : QObject(parent) {\n}\n\nvoid Converter::start() {\n utils.addToLog(\"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(\"Conversion canceled.<\/b>\");\n utils.killed = false;\n win.toggleConversionButton();\n return;\n }\n if (code != 0) {\n utils.addToLog(\"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(\"Conversion complete.<\/b>\");\n utils.addToLog(\"Saved to: \" + utils.getCurrentFilename());\n\n if (win.ui->menuShowFile->isChecked())\n utils.showFileInDirectory();\n}\n<|endoftext|>"} {"text":"\/*\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 \n#include \n#include \n#include \n\nnamespace ox::mc {\n\ntemplate\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\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) {\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\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 ? 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(bytes - 1);\n\n\t\t\/\/ ensure we are copying from little endian represenstation\n\t\tLittleEndian 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(leVal.raw()) << bytes |\n\t\t\t\tstatic_cast(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\nResult 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(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(decoded);\n\t\t\/\/ move sign bit\n\t\tif constexpr(ox::is_signed_v) {\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 - 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\nResult decodeInteger(McInt m) noexcept {\n\tstd::size_t bytesRead;\n\treturn decodeInteger(m.data, 9, &bytesRead);\n}\n\n}\n[ox\/mc] Removes some unnecessary type conversions\/*\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 \n#include \n#include \n#include \n\nnamespace ox::mc {\n\ntemplate\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\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) {\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\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 ? 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(bytes - 1);\n\n\t\t\/\/ ensure we are copying from little endian represenstation\n\t\tLittleEndian 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(leVal.raw()) << bytes |\n\t\t\t\tstatic_cast(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\nResult 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(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(decoded);\n\t\t\/\/ move sign bit\n\t\tif constexpr(ox::is_signed_v) {\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 - 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\nResult decodeInteger(McInt m) noexcept {\n\tstd::size_t bytesRead;\n\treturn decodeInteger(m.data, 9, &bytesRead);\n}\n\n}\n<|endoftext|>"} {"text":"\/*\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 \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 \n# include \n# include \n# include \n# include \n# include \n# include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \/\/ for Qt::escape\n#include \n#include \n#include \n\n#include \n\nnamespace {\n template \n boost::shared_ptr make_shared_ptr( T * t ) {\n return t ? boost::shared_ptr( t ) : boost::shared_ptr() ;\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 \", 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( \"The crypto plugin could not be initialized.
\"\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( new Kleo::GenericAssuanCommandFactory ) )\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(\"The Kleopatra GPG UI Server Module couldn't be initialized.\"\n \"The error given was: %1<\/b>\"\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}\nDon't terminate the uiserver when closing the last dialog.\/*\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 \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 \n# include \n# include \n# include \n# include \n# include \n# include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \/\/ for Qt::escape\n#include \n#include \n#include \n\n#include \n\nnamespace {\n template \n boost::shared_ptr make_shared_ptr( T * t ) {\n return t ? boost::shared_ptr( t ) : boost::shared_ptr() ;\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 \", 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( \"The crypto plugin could not be initialized.
\"\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( new Kleo::GenericAssuanCommandFactory ) )\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(\"The Kleopatra GPG UI Server Module couldn't be initialized.\"\n \"The error given was: %1<\/b>\"\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":"\/*\n * Copyright (C) 2014 Daniel Nicoletti \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 \n#include \n\n#include \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 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 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 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 Headers::headersForResponse() const\n{\n QList ret;\n\n QHash::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 HeadersPrivate::decodeBasicAuthPair(const QString &auth)\n{\n QPair 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}\nsome const & usage\/*\n * Copyright (C) 2014 Daniel Nicoletti \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 \n#include \n\n#include \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 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 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 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 Headers::headersForResponse() const\n{\n QList ret;\n\n QHash::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 HeadersPrivate::decodeBasicAuthPair(const QString &auth)\n{\n QPair 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":"\/*\n * Copyright (C) 2013-2016 Daniel Nicoletti \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 \n#include \n#include \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 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 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 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 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 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 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 &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 ¶ms)\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\"\nSimplify parseBody()\/*\n * Copyright (C) 2013-2016 Daniel Nicoletti \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 \n#include \n#include \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 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 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 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 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 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 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 &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 ¶ms)\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":"#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 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::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* adding unique index to detect collisions#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 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::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":"\/\/ 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\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 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 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 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 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\nchromeos: Fix screen locker tests.\/\/ 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\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 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 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 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 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":"\/\/=======================================================================\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 \n#include \n\n#include \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}\nImplement variables annotation for compound assignment\/\/=======================================================================\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 \n#include \n\n#include \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":"#ifndef BOP_MATRIX_HPP\n#define BOP_MATRIX_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \"Vector.hpp\"\n\n\/*\n\tbop::maths::Matrix class file\n*\/\n\nnamespace bop {\n\tnamespace maths{\n\t\ttemplate\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* 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[size];\n\t\t\t\t\tfor (unsigned int i = 0; i < size; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector(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[height];\n\t\t\t\t\tfor (int i = 0; i < height; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector(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 > 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[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& 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[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&& 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& 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& operator= (const Matrix &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[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& 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& 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& 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& operator*= (Matrix &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* temp = new Vector[this->height];\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\ttemp[i] = Vector(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& 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& operator+= (Matrix &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& operator-= (Matrix &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& 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* 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\n\t\tMatrix operator* (Matrix &mat, const T scalar) {\n\t\t\tMatrix mat_p(mat);\n\t\t\tmat_p *= scalar;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate\n\t\tMatrix operator* (Matrix &mat1, Matrix& mat2) {\n\t\t\tMatrix mat_p(mat1);\n\t\t\tmat_p *= mat2;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate\n\t\tMatrix operator\/ (Matrix &mat, const T scalar) {\n\t\t\tMatrix mat_p(mat)\n\t\t\tmat_p \/= scalar;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate\n\t\tMatrix operator+ (Matrix &mat1, Matrix& mat2) {\n\t\t\tMatrix mat_sum(mat1);\n\t\t\tmat_sum += mat2;\n\t\t\treturn mat_sum;\n\t\t}\n\t\t\n\t\ttemplate\n\t\tMatrix operator- (Matrix &mat1, Matrix& mat2) {\n\t\t\tMatrix 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\n\t\tT determinant(Matrix& mat, Vector& 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\n\t\tT determinant(const Matrix& 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(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 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\n\t\tMatrix identityMatrix(unsigned int size) {\n\t\t\t\/*\n\t\t\t\tReturns an Identity Matrix.\n\t\t\t*\/\n\t\t\tMatrix 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\n\t\tbool invertable(Matrix &mat) {\n\t\t\treturn (mat.square() && determinant(mat) != 0);\n\t\t}\n\t\t\n\t\ttemplate\n\t\tMatrix inverseMatrix(Matrix 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 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\n\t\tMatrix transposeMatrix(Matrix &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 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#endifMissing semicolon#ifndef BOP_MATRIX_HPP\n#define BOP_MATRIX_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \"Vector.hpp\"\n\n\/*\n\tbop::maths::Matrix class file\n*\/\n\nnamespace bop {\n\tnamespace maths{\n\t\ttemplate\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* 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[size];\n\t\t\t\t\tfor (unsigned int i = 0; i < size; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector(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[height];\n\t\t\t\t\tfor (int i = 0; i < height; i++) {\n\t\t\t\t\t\tthis->data[i] = Vector(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 > 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[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& 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[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&& 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& 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& operator= (const Matrix &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[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& 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& 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& 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& operator*= (Matrix &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* temp = new Vector[this->height];\n\t\t\t\t\tfor (int i = 0; i < this->height; i++) {\n\t\t\t\t\t\ttemp[i] = Vector(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& 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& operator+= (Matrix &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& operator-= (Matrix &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& 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* 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\n\t\tMatrix operator* (Matrix &mat, const T scalar) {\n\t\t\tMatrix mat_p(mat);\n\t\t\tmat_p *= scalar;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate\n\t\tMatrix operator* (Matrix &mat1, Matrix& mat2) {\n\t\t\tMatrix mat_p(mat1);\n\t\t\tmat_p *= mat2;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate\n\t\tMatrix operator\/ (Matrix &mat, const T scalar) {\n\t\t\tMatrix mat_p(mat);\n\t\t\tmat_p \/= scalar;\n\t\t\treturn mat_p;\n\t\t}\n\t\t\n\t\ttemplate\n\t\tMatrix operator+ (Matrix &mat1, Matrix& mat2) {\n\t\t\tMatrix mat_sum(mat1);\n\t\t\tmat_sum += mat2;\n\t\t\treturn mat_sum;\n\t\t}\n\t\t\n\t\ttemplate\n\t\tMatrix operator- (Matrix &mat1, Matrix& mat2) {\n\t\t\tMatrix 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\n\t\tT determinant(Matrix& mat, Vector& 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\n\t\tT determinant(const Matrix& 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(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 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\n\t\tMatrix identityMatrix(unsigned int size) {\n\t\t\t\/*\n\t\t\t\tReturns an Identity Matrix.\n\t\t\t*\/\n\t\t\tMatrix 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\n\t\tbool invertable(Matrix &mat) {\n\t\t\treturn (mat.square() && determinant(mat) != 0);\n\t\t}\n\t\t\n\t\ttemplate\n\t\tMatrix inverseMatrix(Matrix 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 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\n\t\tMatrix transposeMatrix(Matrix &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 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":"\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE \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 \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 \r\n#include \r\n#include \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector motionSensors; \/\/Vector of the sensors\r\nvector lights; \/\/Vector of the lights\r\nvector 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; icheck()) {\r\n \/\/active[i]=1;\r\n alert = false;\r\n\t\tcout <<\"halleyula\" <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\"<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\nadded comments\/\/g++ *.cpp -lpthread -lwiringPi -std=c++11\r\n\/\/LATER MET GUI MAKEFILE \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 \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 \r\n#include \r\n#include \/\/compile with -lwiringPi\r\n\r\nusing namespace std;\r\n\r\nvector motionSensors; \/\/Vector of the sensors\r\nvector lights; \/\/Vector of the lights\r\nvector 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; icheck()) {\r\n \/\/active[i]=1;\r\n alert = false;\r\n\t\tcout <<\"halleyula\" <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\"<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":"\/*\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 * .\n *\/\n#include \"ElemAttribute.hpp\"\n\n\n\n#include \n\n\n\n#include \n#include \n\n\n\n#include \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}\nMake sure that a new namespace declaration is generated when an attribute's namespace is the default namespace. (namespace128, namespace130)\/*\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 * .\n *\/\n#include \"ElemAttribute.hpp\"\n\n\n\n#include \n\n\n\n#include \n#include \n\n\n\n#include \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":"#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{}) },\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(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(width) \/ static_cast(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(mousePos.mouseX - m_lastMousePos.mouseX));\n\tfloat deltaY = degsToRadians(static_cast(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}Fixed wrong fps computation#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{}) },\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(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(width) \/ static_cast(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(mousePos.mouseX - m_lastMousePos.mouseX));\n\tfloat deltaY = degsToRadians(static_cast(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":"\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra \n *\n * This 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 \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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( static_cast( 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( gobj ) )\n {\n QIcon icon = qobject_cast( 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();\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( static_cast( 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( parent.internalPointer() );\n\n if( parentItem )\n {\n if( qobject_cast( parentItem ) )\n {\n if( qobject_cast( 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( 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( 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( 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( parent.internalPointer() );\n\n int childCount = -1;\n const QObjectList allChildren = parentItem->children();\n foreach( const QObject * child, allChildren )\n {\n if( qobject_cast( child ) )\n ++childCount;\n if( childCount == row )\n return createIndex( row, column, const_cast( 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( index.internalPointer() );\n GluonEngine::Asset* obj = qobject_cast(static_cast(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( 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( 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( 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( parent.internalPointer() );\n\n GluonCore::GluonObject* newObject = qobject_cast( 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\"\nMove the dropped object in the Project tree to its new parent\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2010 Arjen Hiemstra \n *\n * This 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 \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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( static_cast( 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( gobj ) )\n {\n QIcon icon = qobject_cast( 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();\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( static_cast( 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( parent.internalPointer() );\n\n if( parentItem )\n {\n if( qobject_cast( parentItem ) )\n {\n if( qobject_cast( 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( 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( 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( 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( parent.internalPointer() );\n\n int childCount = -1;\n const QObjectList allChildren = parentItem->children();\n foreach( const QObject * child, allChildren )\n {\n if( qobject_cast( child ) )\n ++childCount;\n if( childCount == row )\n return createIndex( row, column, const_cast( 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( index.internalPointer() );\n GluonEngine::Asset* obj = qobject_cast(static_cast(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( 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(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( 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( 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( parent.internalPointer() );\n\n GluonCore::GluonObject* newObject = qobject_cast( 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":"\/* 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}\nHAL sleep test fix\/* 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":"\/* -*- 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.\n--------------------------------------------------------------------------------------------------*\/\n\n#include \n#include \n\n#if ABC_HOST_API_POSIX\n #include \/\/ EINTR errno\n #if ABC_HOST_API_DARWIN\n #define _XOPEN_SOURCE\n #endif\n #include \/\/ MINSIGSTKSZ\n #include \n #if ABC_HOST_API_BSD\n #include \n #include \n #include \n #elif ABC_HOST_API_LINUX\n #include \n #endif\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::coroutine\n\nnamespace abc {\n\nclass coroutine::context : public noncopyable {\npublic:\n context(std::function 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(&m_aiStack);\n m_uctx.uc_stack.ss_size = sizeof m_aiStack;\n m_uctx.uc_link = puctxReturn;\n ::makecontext(&m_uctx, reinterpret_cast(&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(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 m_fnInnerMain;\n};\n\n\ncoroutine::coroutine() {\n}\n\/*explicit*\/ coroutine::coroutine(std::function fnMain) :\n m_pctx(std::make_shared(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(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 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(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> 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> 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 pcorosched \/*= nullptr*\/\n) {\n if (sm_pcorosched.operator std::shared_ptr 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();\n }\n return *(\n sm_pcorosched = std::move(pcorosched)\n ).operator std::shared_ptr const &();\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nUse SIGSTKSZ instead of MINSIGSTKSZ, which is too little under Linux\/* -*- 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.\n--------------------------------------------------------------------------------------------------*\/\n\n#include \n#include \n\n#if ABC_HOST_API_POSIX\n #include \/\/ EINTR errno\n #if ABC_HOST_API_DARWIN\n #define _XOPEN_SOURCE\n #endif\n #include \/\/ SIGSTKSZ\n #include \n #if ABC_HOST_API_BSD\n #include \n #include \n #include \n #elif ABC_HOST_API_LINUX\n #include \n #endif\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::coroutine\n\nnamespace abc {\n\nclass coroutine::context : public noncopyable {\npublic:\n context(std::function 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(&m_aiStack);\n m_uctx.uc_stack.ss_size = sizeof m_aiStack;\n m_uctx.uc_link = puctxReturn;\n ::makecontext(&m_uctx, reinterpret_cast(&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(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 m_fnInnerMain;\n};\n\n\ncoroutine::coroutine() {\n}\n\/*explicit*\/ coroutine::coroutine(std::function fnMain) :\n m_pctx(std::make_shared(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(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 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(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> 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> 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 pcorosched \/*= nullptr*\/\n) {\n if (sm_pcorosched.operator std::shared_ptr 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();\n }\n return *(\n sm_pcorosched = std::move(pcorosched)\n ).operator std::shared_ptr const &();\n}\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"#include \"DySySim.h\"\n#include \"LibInfoDySySim.h\"\n#include \"SimBlock.h\"\n\n#include \n\n#include \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 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}\nImprove test code#include \"DySySim.h\"\n#include \"LibInfoDySySim.h\"\n#include \"SimBlock.h\"\n\n#include \n\n#include \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 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 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 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 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 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":"\/**\n * This file is part of TelepathyQt\n *\n * @copyright Copyright (C) 2010 Collabora Ltd. \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 \n\n#include \n#include \n#include \n#include \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 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 \n *\n * \\brief The ProtocolInfo class represents a 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 ¶m, 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 * register<\/code> to 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-\" 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\nProtocolInfo: Fix some small doc issues.\/**\n * This file is part of TelepathyQt\n *\n * @copyright Copyright (C) 2010 Collabora Ltd. \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 \n\n#include \n#include \n#include \n#include \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 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 \n *\n * \\brief The ProtocolInfo class represents a 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 ¶m, 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 * register<\/code> to 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-\" 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":"\/\/\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 \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}\nbegin PSM support\/\/\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 \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":"\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#include \"scene.h\"\n#include \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}\nWe shouldn't be totally reversed in our camera position.\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#include \"scene.h\"\n#include \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":"psuedo code for new renderer system.<|endoftext|>"} {"text":"\/**\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}\nFixed compile warning.\/**\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":"\/\/\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 \n#include \n#include \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());\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 \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 const quantizer{ 7 };\n\t\tusing FloorResid = std::pair;\n\t\tstd::vector > 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 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(oss, \"int,int\");\n\trunTest(oss, \"int,float\");\n\trunTest(oss, \"double,int\");\n\trunTest(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}\ntestdat\/uquantum.cpp added Splitter test for fractional delta\/\/\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 \n#include \n#include \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());\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 const split{ .25 };\n\tstd::pair const expPos{ 3L*4L + 3L, 0. };\n\tstd::pair 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 const expNeg{ -4L*4L + 1L, 0. };\n\tstd::pair 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 \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 const quantizer{ 7 };\n\t\tusing FloorResid = std::pair;\n\t\tstd::vector > 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 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(oss, \"int,int\");\n\trunTest(oss, \"int,float\");\n\trunTest(oss, \"double,int\");\n\trunTest(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":"#include \"Controller.h\"\n#include \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}\nwrite and read serial in controller#include \"Controller.h\"\n#include \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":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \n#include \n\n#if qPlatform_POSIX\n#include \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 (p) - 1;\n }\n void* BackendPtrToExposedPtr_ (void* p)\n {\n if (p == nullptr) {\n OhShit_ ();\n }\n return reinterpret_cast (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 (p);\n SetDeadMansLand_ (reinterpret_cast (p), reinterpret_cast (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 (p);\n const HeaderOrFooter_* fp = reinterpret_cast (reinterpret_cast (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 (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 (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\ncosmetic\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/StroikaPreComp.h\"\n\n#include \n#include \n\n#if qPlatform_POSIX\n#include \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 (p) - 1;\n }\n void* BackendPtrToExposedPtr_ (void* p)\n {\n if (p == nullptr) {\n OhShit_ ();\n }\n return reinterpret_cast (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 (p);\n SetDeadMansLand_ (reinterpret_cast (p), reinterpret_cast (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 (p);\n const HeaderOrFooter_* fp = reinterpret_cast (reinterpret_cast (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 (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 (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":"\/*\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& 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 (family), static_cast (socketKind), static_cast (protocol.Value ())); }));\n#elif qPlatform_Windows\n DISABLE_COMPILER_MSC_WARNING_START (28193) \/\/ dump warning about examining sfd\n ThrowErrNoIfNegative (sfd = ::socket (static_cast (family), static_cast (socketKind), static_cast (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 (&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 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 critSec{*this};\n return getsockopt (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 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 (SOL_SOCKET, SO_REUSEADDR, bindFlags.fReUseAddr ? 1 : 0);\n\n sockaddr_storage useSockAddr = sockAddr.As ();\n PlatformNativeHandle sfd = fRep_->GetNativeSocket ();\n#if qPlatform_Windows\n try {\n ThrowErrNoIfNegative (::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 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 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\ncosmetic\/*\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& 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 (family), static_cast (socketKind), static_cast (protocol.Value ())); }));\n#elif qPlatform_Windows\n DISABLE_COMPILER_MSC_WARNING_START (28193) \/\/ dump warning about examining sfd\n ThrowErrNoIfNegative (sfd = ::socket (static_cast (family), static_cast (socketKind), static_cast (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 (&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 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 critSec{*this};\n return getsockopt (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 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 (SOL_SOCKET, SO_REUSEADDR, bindFlags.fReUseAddr ? 1 : 0);\n\n sockaddr_storage useSockAddr = sockAddr.As ();\n PlatformNativeHandle sfd = fRep_->GetNativeSocket ();\n#if qPlatform_Windows\n try {\n ThrowErrNoIfNegative (::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 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 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":"\/*=========================================================================\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 \n#include \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::Pointer\n reader = itk::TransformFileReaderTemplate::New();\n\n typename itk::TransformFileWriterTemplate::Pointer\n writer = itk::TransformFileWriterTemplate::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\nstatic int oneTest(const char *const goodname,const char *const badname)\n{\n typedef typename itk::AffineTransform AffineTransformType;\n typedef typename itk::AffineTransform 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::Pointer\n writer = itk::TransformFileWriterTemplate::New();\n typename itk::TransformFileReaderTemplate::Pointer\n reader = itk::TransformFileReaderTemplate::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::TransformListType * list = reader->GetTransformList();\n typename itk::TransformFileReaderTemplate::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::Pointer\n badwriter = itk::TransformFileWriterTemplate::New();\n typename itk::TransformFileReaderTemplate::Pointer\n badreader = itk::TransformFileReaderTemplate::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 >(goodname);\n error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n\n error_sum += ReadWriteTest< float, itk::ConstantVelocityFieldTransform >(goodname);\n error_sum += ReadWriteTest< float, itk::ConstantVelocityFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::ConstantVelocityFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::ConstantVelocityFieldTransform >(goodname);\n\n error_sum += ReadWriteTest< float, itk::DisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< float, itk::DisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::DisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::DisplacementFieldTransform >(goodname);\n\n error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n\n error_sum += ReadWriteTest< float, itk::GaussianExponentialDiffeomorphicTransform >(goodname);\n error_sum += ReadWriteTest< float, itk::GaussianExponentialDiffeomorphicTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::GaussianExponentialDiffeomorphicTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::GaussianExponentialDiffeomorphicTransform >(goodname);\n\n error_sum += ReadWriteTest< float, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< float, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform >(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\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::Pointer reader;\n reader = itk::TransformFileReaderTemplate::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::TransformListType *list;\n list = reader->GetTransformList();\n typename itk::TransformFileReaderTemplate::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(\"Transforms_float.h5\", \"TransformsBad_float.h5\" );\n const int result2 = secondTest();\n\n const int result3 = oneTest(\"Transforms_double.hdf5\", \"TransformsBad_double.hdf5\" );\n const int result4 = secondTest();\n\n return (\n ( !( result1 == EXIT_SUCCESS && result2 == EXIT_SUCCESS) ) &&\n ( !( result3 == EXIT_SUCCESS && result4 == EXIT_SUCCESS) )\n );\n}\nBUG: Remove InsightLegacy test code from TransformHDF5Test.\/*=========================================================================\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 \n#include \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::Pointer\n reader = itk::TransformFileReaderTemplate::New();\n\n typename itk::TransformFileWriterTemplate::Pointer\n writer = itk::TransformFileWriterTemplate::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\nstatic int oneTest(const char *const goodname,const char *const badname)\n{\n typedef typename itk::AffineTransform AffineTransformType;\n typedef typename itk::AffineTransform 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::Pointer\n writer = itk::TransformFileWriterTemplate::New();\n typename itk::TransformFileReaderTemplate::Pointer\n reader = itk::TransformFileReaderTemplate::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::TransformListType * list = reader->GetTransformList();\n typename itk::TransformFileReaderTemplate::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::Pointer\n badwriter = itk::TransformFileWriterTemplate::New();\n typename itk::TransformFileReaderTemplate::Pointer\n badreader = itk::TransformFileReaderTemplate::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 >(goodname);\n error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n\n error_sum += ReadWriteTest< float, itk::ConstantVelocityFieldTransform >(goodname);\n error_sum += ReadWriteTest< float, itk::ConstantVelocityFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::ConstantVelocityFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::ConstantVelocityFieldTransform >(goodname);\n\n error_sum += ReadWriteTest< float, itk::DisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< float, itk::DisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::DisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::DisplacementFieldTransform >(goodname);\n\n error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< float, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::BSplineSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n\n error_sum += ReadWriteTest< float, itk::GaussianExponentialDiffeomorphicTransform >(goodname);\n error_sum += ReadWriteTest< float, itk::GaussianExponentialDiffeomorphicTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::GaussianExponentialDiffeomorphicTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::GaussianExponentialDiffeomorphicTransform >(goodname);\n\n error_sum += ReadWriteTest< float, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< float, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform >(goodname);\n error_sum += ReadWriteTest< double, itk::GaussianSmoothingOnUpdateDisplacementFieldTransform >(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(\"Transforms_float.h5\", \"TransformsBad_float.h5\" );\n const int result2 = oneTest(\"Transforms_double.hdf5\", \"TransformsBad_double.hdf5\" );\n\n return ( !( result1 == EXIT_SUCCESS && result2 == EXIT_SUCCESS) );\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \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 \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 \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 sections;\n\n\tMEMORY_BASIC_INFORMATION memInfo = { };\n\tmemInfo.RegionSize = 0x1000;\n\tsize_t address = 0;\n\twhile (VirtualQueryEx(process, reinterpret_cast(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(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(data->BaseAddress), [§ions](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 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(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(j->BaseAddress) && sectionAddress < reinterpret_cast(j->BaseAddress) + static_cast(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(§ion);\n\t\t}\n\t}\n}\nfix broken code - how did this work#include \n#include \n#include \n#include \n#include \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 \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 \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 sections;\n\n\tMEMORY_BASIC_INFORMATION memInfo = { };\n\tmemInfo.RegionSize = 0x1000;\n\tsize_t address = 0;\n\twhile (VirtualQueryEx(process, reinterpret_cast(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(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(data->BaseAddress), [§ions](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 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(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(j->BaseAddress) && sectionAddress < reinterpret_cast(j->BaseAddress) + static_cast(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(§ion);\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\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 * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SW_NDARR_HXX\n#define SW_NDARR_HXX\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \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 \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 NodeRanges_t;\n typedef ::std::vector 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\nundoapi: #i115383#: rollback change: make SwNodes ctor protected again\/*************************************************************************\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 * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef SW_NDARR_HXX\n#define SW_NDARR_HXX\n\n#include \n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \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 \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 NodeRanges_t;\n typedef ::std::vector 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":"\/*************************************************************************\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 \n#endif\n#ifndef _LNKBASE_HXX \/\/autogen\n#include \n#endif\n#ifndef _GRFMGR_HXX \/\/autogen\n#include \n#endif\n#ifndef _NDNOTXT_HXX\n#include \n#endif\n\/\/ --> OD, MAV 2005-08-17 #i53025#\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include \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\nINTEGRATION: 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 now inherits also from new class \/*************************************************************************\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 \n#endif\n#ifndef _GRFMGR_HXX \/\/autogen\n#include \n#endif\n#ifndef _NDNOTXT_HXX\n#include \n#endif\n\/\/ --> OD, MAV 2005-08-17 #i53025#\n#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_\n#include \n#endif\n\/\/ <--\n\/\/ --> OD 2007-03-28 #i73788#\n#include \n#include \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 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 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":"\/*\n * DISTRHO Plugin Framework (DPF)\n * Copyright (C) 2012-2021 Filipe Coelho \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 \n#else\n# ifndef STATIC_BUILD\n# include \n# endif\n# include \n# include \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\nDo not export DllMain for static windows builds\/*\n * DISTRHO Plugin Framework (DPF)\n * Copyright (C) 2012-2021 Filipe Coelho \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 \n#else\n# ifndef STATIC_BUILD\n# include \n# endif\n# include \n# include \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":"\/\/ 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 \n#include \n#include \n#include \n#include \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 operator()(torrent* t, void*)\n {\n lock_gil lock;\n return extract >(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(params[\"ti\"]));\n\n std::string url;\n if (params.has_key(\"tracker_url\"))\n {\n url = extract(params[\"tracker_url\"]);\n p.tracker_url = url.c_str();\n }\n if (params.has_key(\"info_hash\"))\n p.info_hash = extract(params[\"info_hash\"]);\n std::string name;\n if (params.has_key(\"name\"))\n {\n name = extract(params[\"name\"]);\n p.name = name.c_str();\n }\n p.save_path = fs::path(extract(params[\"save_path\"]));\n\n std::vector resume_buf;\n if (params.has_key(\"resume_data\"))\n {\n std::string resume = extract(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(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 torrents = s.get_torrents();\n\n for (std::vector::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\")\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\")\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_(\"options_t\")\n .value(\"none\", session::none)\n .value(\"delete_files\", session::delete_files)\n ;\n\n enum_(\"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\", no_init)\n .def(\n init((\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())\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())\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())\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())\n .def(\"tracker_proxy\", allow_threads(&session::tracker_proxy), return_value_policy())\n .def(\"web_seed_proxy\", allow_threads(&session::web_seed_proxy), return_value_policy())\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 >();\n}\nUpdate and clean-up session.cpp in python bindings\/\/ 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 \n#include \n#include \n#include \n#include \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 operator()(torrent* t, void*)\n {\n lock_gil lock;\n return extract >(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(params[\"ti\"]));\n\n std::string url;\n if (params.has_key(\"tracker_url\"))\n {\n url = extract(params[\"tracker_url\"]);\n p.tracker_url = url.c_str();\n }\n if (params.has_key(\"info_hash\"))\n p.info_hash = extract(params[\"info_hash\"]);\n std::string name;\n if (params.has_key(\"name\"))\n {\n name = extract(params[\"name\"]);\n p.name = name.c_str();\n }\n p.save_path = fs::path(extract(params[\"save_path\"]));\n\n std::vector resume_buf;\n if (params.has_key(\"resume_data\"))\n {\n std::string resume = extract(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(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 torrents = s.get_torrents();\n\n for (std::vector::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\")\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\")\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\")\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_(\"options_t\")\n .value(\"none\", session::none)\n .value(\"delete_files\", session::delete_files)\n ;\n\n enum_(\"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\", no_init)\n .def(\n init((\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())\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())\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())\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())\n .def(\"tracker_proxy\", allow_threads(&session::tracker_proxy), return_value_policy())\n .def(\"web_seed_proxy\", allow_threads(&session::web_seed_proxy), return_value_policy())\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 >();\n}\n<|endoftext|>"} {"text":"\/\/ 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 \n#include \n#include \n#include \n#include \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 operator()(torrent* t, void*)\n {\n lock_gil lock;\n return extract >(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(params[\"ti\"]));\n\n std::string url;\n if (params.has_key(\"tracker_url\"))\n {\n url = extract(params[\"tracker_url\"]);\n p.tracker_url = url.c_str();\n }\n if (params.has_key(\"info_hash\"))\n p.info_hash = extract(params[\"info_hash\"]);\n std::string name;\n if (params.has_key(\"name\"))\n {\n name = extract(params[\"name\"]);\n p.name = name.c_str();\n }\n p.save_path = fs::path(extract(params[\"save_path\"]));\n\n std::vector resume_buf;\n if (params.has_key(\"resume_data\"))\n {\n std::string resume = extract(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(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 torrents = s.get_torrents();\n\n for (std::vector::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\")\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\")\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\")\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_(\"options_t\")\n .value(\"none\", session::none)\n .value(\"delete_files\", session::delete_files)\n ;\n\n enum_(\"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\", no_init)\n .def(\n init((\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())\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())\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())\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())\n .def(\"tracker_proxy\", allow_threads(&session::tracker_proxy), return_value_policy())\n .def(\"web_seed_proxy\", allow_threads(&session::web_seed_proxy), return_value_policy())\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 >();\n}\nAdd session.get_cache_status() to the python bindings\/\/ 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 \n#include \n#include \n#include \n#include \n#include \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 operator()(torrent* t, void*)\n {\n lock_gil lock;\n return extract >(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(params[\"ti\"]));\n\n std::string url;\n if (params.has_key(\"tracker_url\"))\n {\n url = extract(params[\"tracker_url\"]);\n p.tracker_url = url.c_str();\n }\n if (params.has_key(\"info_hash\"))\n p.info_hash = extract(params[\"info_hash\"]);\n std::string name;\n if (params.has_key(\"name\"))\n {\n name = extract(params[\"name\"]);\n p.name = name.c_str();\n }\n p.save_path = fs::path(extract(params[\"save_path\"]));\n\n std::vector resume_buf;\n if (params.has_key(\"resume_data\"))\n {\n std::string resume = extract(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(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 torrents = s.get_torrents();\n\n for (std::vector::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\")\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\")\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\")\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_(\"options_t\")\n .value(\"none\", session::none)\n .value(\"delete_files\", session::delete_files)\n ;\n\n enum_(\"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\")\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\", no_init)\n .def(\n init((\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())\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())\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())\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())\n .def(\"tracker_proxy\", allow_threads(&session::tracker_proxy), return_value_policy())\n .def(\"web_seed_proxy\", allow_threads(&session::web_seed_proxy), return_value_policy())\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 >();\n}\n<|endoftext|>"} {"text":"#include \"NodeType.h\"\n#include \"NodeFactory.h\"\n\n#include \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 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 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 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)validate homography input (number of points for estimation)#include \"NodeType.h\"\n#include \"NodeFactory.h\"\n\n#include \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 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 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 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":"#ifndef __BH_VE_CPU_BACKENDS\n#define __BH_VE_CPU_BACKENDS\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"dirent.h\"\n#include \n#include \n#include \"utils.cpp\"\n#include \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 func_storage;\n\/\/typedef std::map handle_storage;\n\ntypedef std::unordered_map func_storage;\ntypedef std::unordered_map 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 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\/_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 symbols, std::string library)\n {\n bool res = true;\n for(std::vector::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\/_.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\ncpu: Fixed that annoying extra \".\" in source-code filenames.#ifndef __BH_VE_CPU_BACKENDS\n#define __BH_VE_CPU_BACKENDS\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"dirent.h\"\n#include \n#include \n#include \"utils.cpp\"\n#include \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 func_storage;\n\/\/typedef std::map handle_storage;\n\ntypedef std::unordered_map func_storage;\ntypedef std::unordered_map 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 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\/_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 symbols, std::string library)\n {\n bool res = true;\n for(std::vector::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\/_.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":"\/\/ --------------------------------------------------------------------------------------------------\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 \n#include \n\n\/\/ STL:\n#include \n\nnamespace malmo\n{\n TimestampedReward::TimestampedReward()\n {\n }\n\n TimestampedReward::TimestampedReward(float reward)\n {\n this->values[0] = static_cast(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 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 :.\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( r.value() );\n }\n }\n \n schemas::Reward TimestampedReward::getAsRewardStructure() const\n {\n schemas::Reward reward;\n for( std::map::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::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::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::const_iterator it = tsf.values.begin(); it!= tsf.values.end(); it++) {\n os << \", \" << it->first << \":\" << it->second;\n }\n return os;\n }\n}\nFix: TimestampedReward::add was broken, causing occasional doubling of rewards.\/\/ --------------------------------------------------------------------------------------------------\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 \n#include \n\n\/\/ STL:\n#include \n\nnamespace malmo\n{\n TimestampedReward::TimestampedReward()\n {\n }\n\n TimestampedReward::TimestampedReward(float reward)\n {\n this->values[0] = static_cast(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 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 :.\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( r.value() );\n }\n }\n \n schemas::Reward TimestampedReward::getAsRewardStructure() const\n {\n schemas::Reward reward;\n for( std::map::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::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::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::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":"\/*\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 \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \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 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 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}\niv: 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.\/*\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 \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \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 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 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":"\/*=========================================================================\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 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}\nERR: Added missing include of \/*=========================================================================\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 \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 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":"\/*\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 \n#include \n#include \n#include \n#include \n#include \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 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; kphi;\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; knumFeatures;\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\nDeleted some OBSOLETE code. Added some OpenCL implementation in preparation for real stuff. Actually mostly consistent use of #ifdef PV_USE_OPENCL to remove implementation.\/*\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 \n#include \n#include \n#include \n#include \n#include \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 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; kphi;\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; knumFeatures;\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":"\/*\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 \n\nusing namespace joynr;\n\nMockLocalCapabilitiesDirectoryCallback::MockLocalCapabilitiesDirectoryCallback()\n : ILocalCapabilitiesCallback(),\n results(),\n semaphore(0) {\n}\n\nvoid MockLocalCapabilitiesDirectoryCallback::capabilitiesReceived(std::vector capabilities) {\n this->results = capabilities;\n semaphore.notify();\n}\n\nstd::vector 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[C++] Make LocalCapabilitiesDirectoryTests more stable\/*\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 \n\nusing namespace joynr;\n\nMockLocalCapabilitiesDirectoryCallback::MockLocalCapabilitiesDirectoryCallback()\n : ILocalCapabilitiesCallback(),\n results(),\n semaphore(1) {\n semaphore.wait();\n}\n\nvoid MockLocalCapabilitiesDirectoryCallback::capabilitiesReceived(std::vector capabilities) {\n this->results = capabilities;\n semaphore.notify();\n}\n\nstd::vector 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":"\/\/ 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 \r\n\r\nnamespace sol {\r\nnamespace detail {\r\ntemplate\r\nstruct are_same : std::true_type {};\r\n\r\ntemplate\r\nstruct are_same : std::integral_constant::value && are_same::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 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(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
(LUA_RIDX_GLOBALS)) {\r\n lua_atpanic(L.get(), detail::atpanic);\r\n open_file(filename);\r\n }\r\n \r\n template\r\n void open_libraries(Args&&... args) {\r\n static_assert(detail::are_same::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)... };\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\r\n T get(U&& key) const {\r\n return global.get(std::forward(key));\r\n }\r\n\r\n template\r\n state& set(T&& key, U&& value) {\r\n global.set(std::forward(key), std::forward(value));\r\n return *this;\r\n }\r\n\r\n template\r\n state& set_function(T&& key, TFx&& fx) {\r\n global.set_function(std::forward(key), std::forward(fx));\r\n return *this;\r\n }\r\n\r\n template\r\n state& set_function(T&& key, TFx&& fx, TM& mem) {\r\n global.set_function(std::forward(key), std::forward(fx), mem);\r\n return *this;\r\n }\r\n\r\n template\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(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_HPPRemove construction from a filename as it's pretty useless\/\/ 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 \r\n\r\nnamespace sol {\r\nnamespace detail {\r\ntemplate\r\nstruct are_same : std::true_type {};\r\n\r\ntemplate\r\nstruct are_same : std::integral_constant::value && are_same::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 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
(LUA_RIDX_GLOBALS)) {\r\n lua_atpanic(L.get(), detail::atpanic);\r\n }\r\n \r\n template\r\n void open_libraries(Args&&... args) {\r\n static_assert(detail::are_same::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)... };\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\r\n T get(U&& key) const {\r\n return global.get(std::forward(key));\r\n }\r\n\r\n template\r\n state& set(T&& key, U&& value) {\r\n global.set(std::forward(key), std::forward(value));\r\n return *this;\r\n }\r\n\r\n template\r\n state& set_function(T&& key, TFx&& fx) {\r\n global.set_function(std::forward(key), std::forward(fx));\r\n return *this;\r\n }\r\n\r\n template\r\n state& set_function(T&& key, TFx&& fx, TM& mem) {\r\n global.set_function(std::forward(key), std::forward(fx), mem);\r\n return *this;\r\n }\r\n\r\n template\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(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":"\/*\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 .\n*\/\n\/**\n * @author Christian \n * @date 2014\n * Solidity commandline compiler.\n *\/\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"BuildInfo.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 and Lefteris , (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()->default_value(false), \"Optimize bytecode for size\")\n\t(\"input-file\", po::value>(), \"input file\")\n\t(\"ast\", po::value(),\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 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[\"\"].append(s);\n\t\t}\n\t}\n\telse\n\t\tfor (string const& infile: vm[\"input-file\"].as>())\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());\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();\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 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}\nSolc evm assembly to either file or stdout option\/*\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 .\n*\/\n\/**\n * @author Christian \n * @date 2014\n * Solidity commandline compiler.\n *\/\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"BuildInfo.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 and Lefteris , (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()->default_value(false), \"Optimize bytecode for size\")\n\t(\"input-file\", po::value>(), \"input file\")\n\t(\"ast\", po::value(),\n\t \"Request to output the AST of the contract. \" outputTypeStr)\n\t(\"asm\", po::value(),\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 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[\"\"].append(s);\n\t\t}\n\t}\n\telse\n\t\tfor (string const& infile: vm[\"input-file\"].as>())\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());\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();\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 contracts = compiler.getContractNames();\n\t\/\/ do we need EVM assembly?\n\tif (vm.count(\"asm\"))\n\t{\n\t\tauto choice = vm[\"asm\"].as();\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":"#include \"MidasThread.h\"\n#include \n#include \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}last commit on this branch, then freezing to integrate midas on a seperate branch#include \"MidasThread.h\"\n#include \n#include \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":"#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 evp;\n for (Int_t iZ=0; iZSetMultBinIndex(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; iMPrintInfo();\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; iMEventMatchesBin(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; iMUpdatePool(trk) > -1)\n break;\n }\n } \n return 0;\n}\nForgotten debug statement#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 evp;\n for (Int_t iZ=0; iZSetMultBinIndex(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; iMPrintInfo();\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; iMEventMatchesBin(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; iMUpdatePool(trk) > -1)\n break;\n }\n } \n return 0;\n}\n<|endoftext|>"} {"text":"Remove in-bunch pileup events in MC<|endoftext|>"} {"text":"\/*=========================================================================\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 \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}\nENH: avoid calling SetOutput - get rid of VTK errors\/*=========================================================================\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 \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":"\/*******************************************************************************\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 \n#include \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 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(\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 hitResult = hitTestInternal(screenPoint.x(), screenPoint.y());\n if (hitResult[0] == 0)\n return Point();\n\n auto hitMatrix = std::unique_ptr(\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(\n m_sceneView->currentViewpointCamera().transformationMatrix());\n\n auto finalMatrix = std::unique_ptr(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.ArcGISArToolkit\", 1, 0, \"ArcGISArView\");\n qmlRegisterType(\"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::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(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\nUpdate AR.md link to point to master branch\/*******************************************************************************\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 \n#include \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 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(\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 hitResult = hitTestInternal(screenPoint.x(), screenPoint.y());\n if (hitResult[0] == 0)\n return Point();\n\n auto hitMatrix = std::unique_ptr(\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(\n m_sceneView->currentViewpointCamera().transformationMatrix());\n\n auto finalMatrix = std::unique_ptr(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.ArcGISArToolkit\", 1, 0, \"ArcGISArView\");\n qmlRegisterType(\"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::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(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":"\/*\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__\nX86: Make the Interrupts class complain less.\/*\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":"\/*\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 .\n *\/\n\n#include \n#include \n#include \n#include \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;\n stdx::optional _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 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();\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> 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 local_ranges;\n auto to_bytes = [](const stdx::optional& 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{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 {\n std::reference_wrapper> _cf_names;\n std::reference_wrapper> _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& cf_names, const std::vector& ranges)\n : _cf_names(std::ref(cf_names))\n , _ranges(std::ref(ranges))\n { }\n virtual_row_iterator(const std::vector& cf_names, const std::vector& 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\n estimates_for_current_keyspace(const database& db, std::vector 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>(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 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(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::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({{ 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(schema, range, slice, fwd);\n }\n};\n\n} \/\/ namespace size_estimates\n\n} \/\/ namespace db\nsize_estimates: convert reader to flat mutation readers\/*\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 .\n *\/\n\n#include \n#include \n#include \n#include \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;\n stdx::optional _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 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 = ≺\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> 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 local_ranges;\n auto to_bytes = [](const stdx::optional& 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{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 {\n std::reference_wrapper> _cf_names;\n std::reference_wrapper> _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& cf_names, const std::vector& ranges)\n : _cf_names(std::ref(cf_names))\n , _ranges(std::ref(ranges))\n { }\n virtual_row_iterator(const std::vector& cf_names, const std::vector& 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\n estimates_for_current_keyspace(const database& db, std::vector 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>(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 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(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::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({{ 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(schema, range, slice, fwd);\n }\n};\n\n} \/\/ namespace size_estimates\n\n} \/\/ namespace db\n<|endoftext|>"} {"text":"\/******************************************************************************\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 \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \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(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 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 ejdb::metadata() noexcept {\n assert(m_db);\n auto r = c_ejdb::metadb(m_db.get());\n return r.empty() ? boost::optional{boost::none} : jbson::document{std::move(r)};\n}\n\ncollection::collection(std::weak_ptr 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> collection::save_document(const jbson::document& data,\n std::error_code& ec) noexcept {\n return save_document(data, false, ec);\n}\n\nboost::optional> 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 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>{boost::none};\n}\n\nboost::optional collection::load_document(std::array 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 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 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(c_ejdb::qresultnum(list)));\n std::vector r;\n r.reserve(s);\n int ns{0};\n for(uint32_t i = 0; i < s; i++) {\n auto data = reinterpret_cast(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 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 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\nFix load_document\/******************************************************************************\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 \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \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(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 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 ejdb::metadata() noexcept {\n assert(m_db);\n auto r = c_ejdb::metadb(m_db.get());\n return r.empty() ? boost::optional{boost::none} : jbson::document{std::move(r)};\n}\n\ncollection::collection(std::weak_ptr 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> collection::save_document(const jbson::document& data,\n std::error_code& ec) noexcept {\n return save_document(data, false, ec);\n}\n\nboost::optional> 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 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>{boost::none};\n}\n\nboost::optional collection::load_document(std::array 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 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 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(c_ejdb::qresultnum(list)));\n std::vector r;\n r.reserve(s);\n int ns{0};\n for(uint32_t i = 0; i < s; i++) {\n auto data = reinterpret_cast(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 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 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":"dbaccess: RowSet.cxx: update m_bIsInsertRow<|endoftext|>"} {"text":"\/\/\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}}Partial implementation of JSON reading\/\/\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 \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":"#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\nbug fix#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":"#pragma once\n\n#include \n#include \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 \n void lock(F func, Args... args) {\n while (_flag.test_and_set(std::memory_order_acquire)) {\n F(std::forward(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};\nAdded spinlock with exponential backoff.#pragma once\n\n#include \n#include \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":"\/*\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 \nFix a redeclaration warning\/*\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":"\/\/ Scintilla source code edit control\n\/** @file LexDMIS.cxx\n ** Lexer for DMIS.\n **\/\n\/\/ Copyright 1998-2005 by Neil Hodgson \n\/\/ Copyright 2013-2014 by Andreas Tscharner \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n\n#include \n#include \n#include \n#include \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= (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);\nAdd missing not sign to fix DMIS label highlighting\/\/ Scintilla source code edit control\n\/** @file LexDMIS.cxx\n ** Lexer for DMIS.\n **\/\n\/\/ Copyright 1998-2005 by Neil Hodgson \n\/\/ Copyright 2013-2014 by Andreas Tscharner \n\/\/ The License.txt file describes the conditions under which this software may be distributed.\n\n\n#include \n#include \n#include \n#include \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= (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":"\/*\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 \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 \n#import \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 \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\niOS: Remove an extra timer init in the sample browser\/*\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 \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 \n#import \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 \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":"\/\/ 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(\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\nMove 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\/\/ 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(\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":"\/****************************************************************************\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 \n#ifdef GL\n#include \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}\nFix freeing of backend instance\/****************************************************************************\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 \n#ifdef GL\n#include \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":"\/*\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 \n#include \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 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}Replace IAS pending flags magic number with constants\/*\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 \n#include \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 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":"\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 \n#include \n\n#include \"exception\"\n\n#ifndef __has_include\n#define __has_include(inc) 0\n#endif\n\n#ifdef __APPLE__\n #include \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()\n #include \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()\n static std::terminate_handler __terminate_handler;\n static std::unexpected_handler __unexpected_handler;\n#endif \/\/ __has_include()\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\nImplement std::exception_ptr under libsupc++.\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 \n#include \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 \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()\n #include \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()\n static std::terminate_handler __terminate_handler;\n static std::unexpected_handler __unexpected_handler;\n#endif \/\/ __has_include()\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(this)) __exception_ptr::exception_ptr(\n reinterpret_cast(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(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":"#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 \n#include \n#include \/\/For char conversion\n#include \/\/For char conversion\n\n\ndouble get_average_error(std::vector 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 new_inputs = training_data.data.at(i);\n classifier.set_input_values(new_inputs);\n classifier.classify();\n\n for(int j=0; j all_total_errors;\n\n for(int i=0; i < training_data.data.size(); i++)\n {\n std::vector new_inputs = training_data.data.at(i);\n classifier.set_input_values(new_inputs);\n classifier.classify();\n\n std::vector 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}\nFound some magic numbers, which I frown upon#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 \n#include \n#include \/\/For char conversion\n#include \/\/For char conversion\n\n\ndouble get_average_error(std::vector 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 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 updated_outputs = network.output_layer;\n\n int updated_outputs_size = updated_outputs.size();\n for(int k=0; k all_total_errors;\n int training_data_size = training_data.data.size();\n\n for(int i=0; i new_inputs = training_data.data.at(i);\n classifier.set_input_values(new_inputs);\n classifier.classify();\n\n std::vector 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":"\/*\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=\"<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=\"<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=\"<Adding chi2 of the fit. (Marian)\/*\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=\"<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=\"<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=\"<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=\"<"} {"text":"\/*=========================================================================\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 \n#include \n#include \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}\nENH (#976): Check for more events in QmitkAbortEventFilter; use typedef for GuardedPtr\/*=========================================================================\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 \n#include \n#include \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":"#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 \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(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 \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(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 \n static inline T* as(Object* obj) {\n if(!kind_of(obj)) {\n TypeError::raise(T::type, obj);\n }\n\n return static_cast(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 \n static inline const T* as(const Object* obj) {\n if(!kind_of(obj)) {\n TypeError::raise(T::type, obj);\n }\n\n return static_cast(obj);\n }\n\n \/**\n * A specialized version for completeness.\n *\/\n template <>\n SPECIALIZATION_STORAGE Object* as(Object* obj) {\n return obj;\n }\n\n \/**\n * A specialized version for completeness.\n *\/\n template <>\n SPECIALIZATION_STORAGE const Object* as(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 \n static inline T* as_instance(Object* obj) {\n if(!instance_of(obj)) {\n TypeError::raise(T::type, obj);\n }\n\n return static_cast(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 \n static inline const T* as_instance(const Object* obj) {\n if(!instance_of(obj)) {\n TypeError::raise(T::type, obj);\n }\n\n return static_cast(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 \n static inline T* try_as(Object* obj) {\n if(!kind_of(obj)) {\n return NULL;\n }\n\n return static_cast(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 \n static inline const T* try_as(const Object* obj) {\n if(!kind_of(obj)) {\n return NULL;\n }\n\n return static_cast(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 \n static inline T* try_as_instance(Object* obj) {\n if(!instance_of(obj)) {\n return NULL;\n }\n\n return static_cast(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 \n static inline const T* try_as_instance(const Object* obj) {\n if(!instance_of(obj)) {\n return NULL;\n }\n\n return static_cast(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 \n static inline T* nil() { return static_cast(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 \n static inline T* force_as(ObjectHeader* obj) {\n return reinterpret_cast(obj);\n }\n\n template \n static inline const T* force_as(const ObjectHeader* obj) {\n return reinterpret_cast(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\nFix a __GNUC__ check to work with GCC 5#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 \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(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 \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(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 \n static inline T* as(Object* obj) {\n if(!kind_of(obj)) {\n TypeError::raise(T::type, obj);\n }\n\n return static_cast(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 \n static inline const T* as(const Object* obj) {\n if(!kind_of(obj)) {\n TypeError::raise(T::type, obj);\n }\n\n return static_cast(obj);\n }\n\n \/**\n * A specialized version for completeness.\n *\/\n template <>\n SPECIALIZATION_STORAGE Object* as(Object* obj) {\n return obj;\n }\n\n \/**\n * A specialized version for completeness.\n *\/\n template <>\n SPECIALIZATION_STORAGE const Object* as(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 \n static inline T* as_instance(Object* obj) {\n if(!instance_of(obj)) {\n TypeError::raise(T::type, obj);\n }\n\n return static_cast(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 \n static inline const T* as_instance(const Object* obj) {\n if(!instance_of(obj)) {\n TypeError::raise(T::type, obj);\n }\n\n return static_cast(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 \n static inline T* try_as(Object* obj) {\n if(!kind_of(obj)) {\n return NULL;\n }\n\n return static_cast(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 \n static inline const T* try_as(const Object* obj) {\n if(!kind_of(obj)) {\n return NULL;\n }\n\n return static_cast(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 \n static inline T* try_as_instance(Object* obj) {\n if(!instance_of(obj)) {\n return NULL;\n }\n\n return static_cast(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 \n static inline const T* try_as_instance(const Object* obj) {\n if(!instance_of(obj)) {\n return NULL;\n }\n\n return static_cast(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 \n static inline T* nil() { return static_cast(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 \n static inline T* force_as(ObjectHeader* obj) {\n return reinterpret_cast(obj);\n }\n\n template \n static inline const T* force_as(const ObjectHeader* obj) {\n return reinterpret_cast(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":"#ifndef __GLOBALS_HPP_INCLUDED\n#define __GLOBALS_HPP_INCLUDED\n\n#include \n#include \n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include \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 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 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\nBugikorjaus: `WINDOW_WIDTH`, `WINDOW_HEIGHT` & `ASPECT_RATIO`.#ifndef __GLOBALS_HPP_INCLUDED\n#define __GLOBALS_HPP_INCLUDED\n\n#include \n#include \n\n\/\/ Include GLEW\n#ifndef __GL_GLEW_H_INCLUDED\n#define __GL_GLEW_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLFW\n#ifndef __GLFW3_H_INCLUDED\n#define __GLFW3_H_INCLUDED\n#include \n#endif\n\n\/\/ Include GLM\n#ifndef __GLM_GLM_HPP_INCLUDED\n#define __GLM_GLM_HPP_INCLUDED\n#include \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 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 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":"\/\/ 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 .\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 \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 \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::iterator Temp=Stream.begin();\r\n while (Temp!=Stream.end())\r\n {\r\n std::map::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+1MaximumDataPacketSize)\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\/\/ 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 .\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 \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 \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::iterator Temp=Stream.begin();\r\n while (Temp!=Stream.end())\r\n {\r\n std::map::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+1MaximumDataPacketSize)\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":"#include \"gd.h\"\n#include \"vw.h\"\n#include \"lrq.h\"\n#include \"rand48.h\"\n#include \n\nnamespace LRQ {\n\n struct LRQstate {\n vw* all;\n bool lrindices[256];\n size_t orig_size[256];\n std::vector 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::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::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&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 ();\n if (vm_file.count(\"random_seed\")) random_seed = vm_file[\"random_seed\"].as ();\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 > ();\n\n \/\/ TODO: doesn't work for non-printable stuff\n \n stringstream ss;\n for (vector::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 > ();\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::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<set_end_pass (reset_seed);\n\n \/\/ TODO: leaks memory ?\n return l;\n }\n}\ndropout mmf#include \"gd.h\"\n#include \"vw.h\"\n#include \"lrq.h\"\n#include \"rand48.h\"\n#include \n\nnamespace LRQ {\n\n struct LRQstate {\n vw* all;\n bool lrindices[256];\n size_t orig_size[256];\n std::vector 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::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::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&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 ();\n if (vm_file.count(\"random_seed\")) random_seed = vm_file[\"random_seed\"].as ();\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 > ();\n\n \/\/ TODO: doesn't work for non-printable stuff\n \n stringstream ss;\n for (vector::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 > ();\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::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<set_end_pass (reset_seed);\n\n \/\/ TODO: leaks memory ?\n return l;\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\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; iNumberOfSubPieces; 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}\nENH: Changes necessary to get streaming woring in ParaView.\/*=========================================================================\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; iNumberOfSubPieces; 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":"\/\/ 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 \n#include \n\n#include \n\nnamespace RosettaStone::Generic\n{\n\/\/! A list of play requirements that needs a target.\nconstexpr std::array 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 GetValidTargets(Entity* source)\n{\n std::vector 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(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(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\nfeat(card-impl): Add code to consider PlayReq::REQ_DAMAGED_TARGET\/\/ 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 \n#include \n\n#include \n\nnamespace RosettaStone::Generic\n{\n\/\/! A list of play requirements that needs a target.\nconstexpr std::array 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 GetValidTargets(Entity* source)\n{\n std::vector 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(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(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":"\/\/\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 \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(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> 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[exotica_ilqg_solver] Upgrade get_num_positions etc.\/\/\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 \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(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> 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":"\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen\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 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 Album::addTrack(std::shared_ptr 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 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 )\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::create(DBConnection dbConnection, const std::string& title )\n{\n auto album = std::make_shared( 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}\nAlbum: Sort tracks by track number\/*****************************************************************************\n * Media Library\n *****************************************************************************\n * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs\n *\n * Authors: Hugo Beauzée-Luyssen\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 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 Album::addTrack(std::shared_ptr 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 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 )\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::create(DBConnection dbConnection, const std::string& title )\n{\n auto album = std::make_shared( 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":"\/*\nDudu Faz Serviço\nhttps:\/\/www.urionlinejudge.com.br\/judge\/pt\/problems\/view\/1610\n*\/\n\n#include \n#include \n#include \n\nusing namespace std;\n\nbool checarCiclos(vector> &adj);\nbool checarCiclos(int origem, vector> &adj, vector &visitado, vector &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> 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> &adj) {\n int N = adj.size();\n vector visitado(N);\n vector 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> &adj, vector &visitado, vector &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}URI Online Judge - 1610 - Dudu faz serviço\/*\nDudu Faz Serviço\nhttps:\/\/www.urionlinejudge.com.br\/judge\/pt\/problems\/view\/1610\n*\/\n\n#include \n#include \n#include \n\nusing namespace std;\n\nbool checarCiclos(vector> &adj);\nbool checarCiclos(int origem, vector> &adj, vector &visitado, vector &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> 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> &adj) {\n int N = adj.size();\n vector visitado(N, false);\n vector 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> &adj, vector &visitado, vector &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":"#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\": , -- 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([](const Val& val) -> acmacs::time_series::parameters {\n if constexpr (std::is_same_v) {\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()};\n }\n AD_WARNING(\"unrecognized interval specification: {}, month assumed\", val);\n return {\"month\"sv};\n }\n else if constexpr (std::is_same_v) {\n return {val.template to()};\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(), 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(), 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":"#pragma once\n\n#include \n#include \n#include \n\nnamespace agency\n{\nnamespace detail\n{\n\n\ntemplate>\nclass boxed_value\n{\n public:\n using allocator_type = typename std::allocator_traits::template rebind_alloc;\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::value\n >::type>\n __AGENCY_ANNOTATION\n explicit boxed_value(Args... args)\n : data_(agency::detail::allocate_unique(allocator_type(), std::forward(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::value\n >::type>\n __AGENCY_ANNOTATION\n boxed_value& operator=(U&& other)\n {\n value() = std::forward(other);\n return *this;\n }\n\n private:\n agency::detail::unique_ptr> data_;\n};\n\n\n\/\/ when the allocator is std::allocator, we can just put this on the stack\ntemplate\nclass boxed_value>\n{\n public:\n using allocator_type = std::allocator;\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::value\n >::type>\n __AGENCY_ANNOTATION\n explicit boxed_value(Args&&... args)\n : value_(std::forward(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::value\n >::type>\n __AGENCY_ANNOTATION\n boxed_value& operator=(U&& other)\n {\n value() = std::forward(other);\n return *this;\n }\n\n private:\n value_type value_;\n};\n\n\ntemplate\n__AGENCY_ANNOTATION\nboxed_value allocate_boxed(const Alloc&, Args&&... args)\n{\n return boxed_value(std::forward(args)...);\n}\n\n\n} \/\/ end detail\n} \/\/ end agency\n\nAdd assignment operators to boxed_value#pragma once\n\n#include \n#include \n#include \n\nnamespace agency\n{\nnamespace detail\n{\n\n\ntemplate>\nclass boxed_value\n{\n public:\n using allocator_type = typename std::allocator_traits::template rebind_alloc;\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::value\n >::type>\n __AGENCY_ANNOTATION\n explicit boxed_value(Args... args)\n : data_(agency::detail::allocate_unique(allocator_type(), std::forward(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::value\n >::type>\n __AGENCY_ANNOTATION\n boxed_value& operator=(U&& other)\n {\n value() = std::forward(other);\n return *this;\n }\n\n private:\n agency::detail::unique_ptr> data_;\n};\n\n\n\/\/ when the allocator is std::allocator, we can just put this on the stack\ntemplate\nclass boxed_value>\n{\n public:\n using allocator_type = std::allocator;\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::value\n >::type>\n __AGENCY_ANNOTATION\n explicit boxed_value(Args&&... args)\n : value_(std::forward(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::value\n >::type>\n __AGENCY_ANNOTATION\n boxed_value& operator=(U&& other)\n {\n value() = std::forward(other);\n return *this;\n }\n\n private:\n value_type value_;\n};\n\n\ntemplate\n__AGENCY_ANNOTATION\nboxed_value allocate_boxed(const Alloc&, Args&&... args)\n{\n return boxed_value(std::forward(args)...);\n}\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<|endoftext|>"} {"text":"\/*=========================================================================\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 \n#include \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(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(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(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(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(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}\nfix for warnings and other bad things\/*=========================================================================\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 \n#include \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(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(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(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(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(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":"#include \"ImageThresholder.h\"\n#include \n#include \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 \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 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\nplaceholder for code#include \"ImageThresholder.h\"\n#include \n#include \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 \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 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":"#include \"hornet\/java.hh\"\n\n#include \"hornet\/translator.hh\"\n#include \"hornet\/vm.hh\"\n\n#include \n\n#include \n#include \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\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 _mimic_stack;\n std::vector _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 T llvm_translator::trampoline()\n{\n verifyFunction(*_func, PrintMessageAction);\n return reinterpret_cast(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();\n\n return fp();\n}\n\n}\nllvm: Integer arithmetic#include \"hornet\/java.hh\"\n\n#include \"hornet\/translator.hh\"\n#include \"hornet\/vm.hh\"\n\n#include \n\n#include \n#include \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\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 _mimic_stack;\n std::vector _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 T llvm_translator::trampoline()\n{\n verifyFunction(*_func, PrintMessageAction);\n return reinterpret_cast(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();\n\n return fp();\n}\n\n}\n<|endoftext|>"} {"text":"#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 e = 21;\n auto ret = e.map(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n const tl::expected e = 21;\n auto ret = e.map(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n tl::expected e = 21;\n auto ret = std::move(e).map(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n const tl::expected e = 21;\n auto ret = std::move(e).map(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n tl::expected 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 e(tl::unexpect, 21);\n auto ret = e.map(mul2);\n REQUIRE(!ret);\n REQUIRE(ret.error() == 21);\n }\n\n {\n tl::expected 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 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 e = 21;\n auto ret = e.map(ret_void);\n REQUIRE(ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n const tl::expected e = 21;\n auto ret = e.map(ret_void);\n REQUIRE(ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n tl::expected e = 21;\n auto ret = std::move(e).map(ret_void);\n REQUIRE(ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n const tl::expected e = 21;\n auto ret = std::move(e).map(ret_void);\n REQUIRE(ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n tl::expected e(tl::unexpect, 21);\n auto ret = e.map(ret_void);\n REQUIRE(!ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n const tl::expected e(tl::unexpect, 21);\n auto ret = e.map(ret_void);\n REQUIRE(!ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n tl::expected e(tl::unexpect, 21);\n auto ret = std::move(e).map(ret_void);\n REQUIRE(!ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n const tl::expected e(tl::unexpect, 21);\n auto ret = std::move(e).map(ret_void);\n REQUIRE(!ret);\n STATIC_REQUIRE(\n (std::is_same>::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 e = 21;\n auto ret = e.map_error(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 21);\n }\n\n {\n const tl::expected e = 21;\n auto ret = e.map_error(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 21);\n }\n\n {\n tl::expected 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 e = 21;\n auto ret = std::move(e).map_error(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 21);\n }\n\n {\n tl::expected 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 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 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 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(21 * 2); };\n auto fail = [](auto a) { return tl::expected(tl::unexpect, 17); };\n\n {\n tl::expected e = 21;\n auto ret = e.and_then(succeed);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n const tl::expected e = 21;\n auto ret = e.and_then(succeed);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n tl::expected 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 e = 21;\n auto ret = std::move(e).and_then(succeed);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n tl::expected e = 21;\n auto ret = e.and_then(fail);\n REQUIRE(!ret);\n REQUIRE(ret.error() == 17);\n }\n\n {\n const tl::expected e = 21;\n auto ret = e.and_then(fail);\n REQUIRE(!ret);\n REQUIRE(ret.error() == 17);\n }\n\n {\n tl::expected 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 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 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 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 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 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 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 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 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 e(tl::unexpect, 21);\n auto ret = std::move(e).and_then(fail);\n REQUIRE(!ret);\n REQUIRE(ret.error() == 21);\n }\n}\nFix tests#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 e = 21;\n auto ret = e.map(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n const tl::expected e = 21;\n auto ret = e.map(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n tl::expected e = 21;\n auto ret = std::move(e).map(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n const tl::expected e = 21;\n auto ret = std::move(e).map(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n tl::expected 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 e(tl::unexpect, 21);\n auto ret = e.map(mul2);\n REQUIRE(!ret);\n REQUIRE(ret.error() == 21);\n }\n\n {\n tl::expected 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 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 e = 21;\n auto ret = e.map(ret_void);\n REQUIRE(ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n const tl::expected e = 21;\n auto ret = e.map(ret_void);\n REQUIRE(ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n tl::expected e = 21;\n auto ret = std::move(e).map(ret_void);\n REQUIRE(ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n const tl::expected e = 21;\n auto ret = std::move(e).map(ret_void);\n REQUIRE(ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n tl::expected e(tl::unexpect, 21);\n auto ret = e.map(ret_void);\n REQUIRE(!ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n const tl::expected e(tl::unexpect, 21);\n auto ret = e.map(ret_void);\n REQUIRE(!ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n tl::expected e(tl::unexpect, 21);\n auto ret = std::move(e).map(ret_void);\n REQUIRE(!ret);\n STATIC_REQUIRE(\n (std::is_same>::value));\n }\n\n {\n const tl::expected e(tl::unexpect, 21);\n auto ret = std::move(e).map(ret_void);\n REQUIRE(!ret);\n STATIC_REQUIRE(\n (std::is_same>::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 e = 21;\n auto ret = e.map_error(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 21);\n }\n\n {\n const tl::expected e = 21;\n auto ret = e.map_error(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 21);\n }\n\n {\n tl::expected 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 e = 21;\n auto ret = std::move(e).map_error(mul2);\n REQUIRE(ret);\n REQUIRE(*ret == 21);\n }\n\n {\n tl::expected 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 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 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 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(21 * 2); };\n auto fail = [](auto a) { return tl::expected(tl::unexpect, 17); };\n\n {\n tl::expected e = 21;\n auto ret = e.and_then(succeed);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n const tl::expected e = 21;\n auto ret = e.and_then(succeed);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n tl::expected 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 e = 21;\n auto ret = std::move(e).and_then(succeed);\n REQUIRE(ret);\n REQUIRE(*ret == 42);\n }\n\n {\n tl::expected e = 21;\n auto ret = e.and_then(fail);\n REQUIRE(!ret);\n REQUIRE(ret.error() == 17);\n }\n\n {\n const tl::expected e = 21;\n auto ret = e.and_then(fail);\n REQUIRE(!ret);\n REQUIRE(ret.error() == 17);\n }\n\n {\n tl::expected 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 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 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 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 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 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 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 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 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 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":"\n#include \"dirs.h\"\n\n#include \n\n#ifdef __WIN32__\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#endif\n\n#include \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\nChanges to App dir on linux and OSX\n#include \"dirs.h\"\n\n#include \n\n#ifdef __WIN32__\n#include \n#include \n#include \n#else\n#include \n#include \n#include \n#endif\n\n#include \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":"\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 .\n *\/\n\n\n#include \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 db;\n sharded auth_service;\n sharded 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}\ntests\/gossip_test: Use RAII for orderly destruction\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 .\n *\/\n\n\n#include \n\n#include \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 db;\n sharded auth_service;\n sharded 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":"\n#include \"gtest.h\"\n\n#include \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\ntests: Add stderr capture & some minor fixes\n#include \"gtest.h\"\n\n#include \n#include \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":"\/\/ clickStoreRGB.cpp : ̨Ӧóڵ㡣\n\/\/\n\n#include \"stdafx.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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 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_ _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::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: \" <修正了能够识别的格式播放完时候退出未响应的bug\/\/ clickStoreRGB.cpp : ̨Ӧóڵ㡣\n\/\/\n\n#include \"stdafx.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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 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_ _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::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: \" <"} {"text":"#ifndef OPERATOR_HH\n#define OPERATOR_HH\n\n\n#include \n#include \n\n#include \"coefficients.hh\"\n#include \"vector.hh\"\n\n#ifdef AS_LIB\n#include \n#endif\n\n\ntemplate \nclass VectorExchange\n : public Dune::CommDataHandleIF, 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 \n void gather(MessageBuffer& buff, const EntityType& e ) const\n {\n buff.write(u_[mapper_.map(e)]);\n }\n\n template \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 \nclass SpaceOperator\n{\npublic:\n typedef Dune::MultipleCodimMultipleGeomTypeMapper Mapper;\n typedef VectorExchange VE;\n\n SpaceOperator(std::shared_ptr gv, std::shared_ptr >& coeffs)\n : gv_(gv), coefficients_(coeffs), mapper_(*gv)\n {}\n\n SpaceOperator(std::shared_ptr gv, std::shared_ptr >& 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, 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_;\n std::shared_ptr > 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_, 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\nfix numerical flux for negative values#ifndef OPERATOR_HH\n#define OPERATOR_HH\n\n\n#include \n#include \n\n#include \"coefficients.hh\"\n#include \"vector.hh\"\n\n#ifdef AS_LIB\n#include \n#endif\n\n\ntemplate \nclass VectorExchange\n : public Dune::CommDataHandleIF, 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 \n void gather(MessageBuffer& buff, const EntityType& e ) const\n {\n buff.write(u_[mapper_.map(e)]);\n }\n\n template \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 \nclass SpaceOperator\n{\npublic:\n typedef Dune::MultipleCodimMultipleGeomTypeMapper Mapper;\n typedef VectorExchange VE;\n\n SpaceOperator(std::shared_ptr gv, std::shared_ptr >& coeffs)\n : gv_(gv), coefficients_(coeffs), mapper_(*gv)\n {}\n\n SpaceOperator(std::shared_ptr gv, std::shared_ptr >& 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, 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_;\n std::shared_ptr > 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_, 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":"\/*\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 ftHelper;\n FontManager fontManager;\n \n shared_ptr font1;\n shared_ptr font2;\n shared_ptr 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 ¶ms);\n shared_ptr loadFontSafely(const string &fileName);\n void drawFontSafely(shared_ptr &font, float size, float x, float y, float direction = +1);\n};\n\nvoid Application::setup()\n{\n ftHelper = make_shared();\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 ¶ms)\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 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 &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))\nTWEAKING samples\/FontGenerator PROJECT\/*\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 ftHelper;\n FontManager fontManager;\n \n vector> 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 ¶ms);\n void loadFontSafely(const string &fileName, bool useMipmap = false);\n void drawFonts(float size);\n};\n\nvoid Application::setup()\n{\n ftHelper = make_shared();\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 ¶ms)\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":"\/\/ 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 GetNativeFunction(\n v8::Handle name);\n\n private:\n static v8::Handle PostMessage(const v8::Arguments& args);\n static v8::Handle SendSyncMessage(const v8::Arguments& args);\n};\n\nXWalkExtensionV8Wrapper::XWalkExtensionV8Wrapper()\n : v8::Extension(\"xwalk\", kSource_xwalk_api) {\n}\n\nv8::Handle\nXWalkExtensionV8Wrapper::GetNativeFunction(v8::Handle 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();\n}\n\nv8::Handle 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 converter(\n content::V8ValueConverter::create());\n scoped_ptr 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 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\nMake lint.py ignore a closing parentheses\/\/ 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 GetNativeFunction(\n v8::Handle name);\n\n private:\n static v8::Handle PostMessage(const v8::Arguments& args);\n static v8::Handle SendSyncMessage(const v8::Arguments& args);\n};\n\nXWalkExtensionV8Wrapper::XWalkExtensionV8Wrapper()\n : v8::Extension(\"xwalk\", kSource_xwalk_api) {\n}\n\nv8::Handle\nXWalkExtensionV8Wrapper::GetNativeFunction(v8::Handle 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();\n}\n\nv8::Handle 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 converter(\n content::V8ValueConverter::create());\n scoped_ptr 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 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":"\/*\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 \n#include \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();\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();\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* 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 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\nmove closing of files outside of file pool mutex\/*\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 \n#include \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();\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();\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* 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 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":"\/*\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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* attributesInfo);\n void processNamespaceAttributes(PSVIAttributeList* psviAttributes, const RefVectorOf* 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* 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* fIdMap;\n RefVectorOf* fDefinedIds;\n RefArrayVectorOf* fIdNames;\n RefArrayVectorOf* fObjectLocations;\n \n\tRefHashTableOf* fPrefixMap;\n RefArrayVectorOf* fNamespaces;\n \n\tValueVectorOf* fNSAttributes; \/\/REVISIT dont need if NSAttrs in different object\n\tValueStackOf* fElementChildren;\n\t\t\n\tRefVectorOf* fAttributesInfo;\n};\n\n\n#endif\n\nHandle partial PSVIElement\/*\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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* attributesInfo);\n void processNamespaceAttributes(PSVIAttributeList* psviAttributes, const RefVectorOf* 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* 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* fIdMap;\n RefVectorOf* fDefinedIds;\n RefArrayVectorOf* fIdNames;\n RefArrayVectorOf* fObjectLocations;\n \n\tRefHashTableOf* fPrefixMap;\n RefArrayVectorOf* fNamespaces;\n \n\tValueVectorOf* fNSAttributes; \/\/REVISIT dont need if NSAttrs in different object\n\tValueStackOf* fElementChildren;\n\t\t\n\tRefVectorOf* fAttributesInfo;\n};\n\n\n#endif\n\n<|endoftext|>"} {"text":"- ExtINT implemented (some progress with FreeBSD 5.3 boot cd) - fixed a warning<|endoftext|>"} {"text":"#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 \n#include \n#include \n#include \n#include \n\n#include \/\/ 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 ¤tTracer, 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 ¤tTracer)\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(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 ¤tTracer, 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 &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(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}\nBugfixes (level progress)#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 \n#include \n#include \n#include \n#include \n\n#include \/\/ 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 ¤tTracer, 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 ¤tTracer)\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(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 ¤tTracer, 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 &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(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":"#include \n#include \n#include \n#include \n#include \n\n\/\/ [hash.combine]\n\nstruct X {\n int v;\n};\nstruct Y { };\nstruct Z { };\n\ntemplate <> struct std::hash {\n constexpr std::size_t operator()(X x) const noexcept { return x.v; }\n};\ntemplate <> struct std::hash {\n std::size_t operator()(Y) const { return 0; }\n};\ntemplate <> struct std::hash : std::hash { };\n\ntemplate constexpr bool is_hash_combinable = requires { jegp::hash_combine(std::declval()...); };\n\nconstexpr void test_hash_combine() {\n static_assert(not is_hash_combinable<>);\n static_assert(not is_hash_combinable);\n static_assert(not is_hash_combinable);\n static_assert(not is_hash_combinable);\n static_assert(not is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(not is_hash_combinable);\n static_assert(not is_hash_combinable);\n static_assert(not is_hash_combinable);\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 constexpr bool is_static_downcastable = requires {\n jegp::static_downcast(std::declval());\n};\n\ntemplate \n requires(\n std::is_same_v>and std::is_same_v> and\n not std::is_same_v and std::is_base_of_v)\nconstexpr void assert_is_static_downcastable() {\n auto ok = [](bool b) { return b == ExpectedToPass; };\n\n static_assert(ok(is_static_downcastable));\n static_assert(ok(is_static_downcastable));\n static_assert(ok(is_static_downcastable));\n static_assert(ok(is_static_downcastable));\n\n static_assert(not is_static_downcastable);\n static_assert(ok(is_static_downcastable));\n static_assert(not is_static_downcastable);\n static_assert(ok(is_static_downcastable));\n\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\n static_assert(ok(is_static_downcastable));\n static_assert(ok(is_static_downcastable));\n\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\n static_assert(ok(is_static_downcastable));\n\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\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();\n assert_is_static_downcastable();\n assert_is_static_downcastable();\n assert_is_static_downcastable();\n}\n\nconsteval void test() {\n test_hash_combine();\n test_static_downcast();\n}\n\nint main() { test(); }\nrefactor: #include #include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ [hash.combine]\n\nstruct X {\n int v;\n};\nstruct Y { };\nstruct Z { };\n\ntemplate <> struct std::hash {\n constexpr std::size_t operator()(X x) const noexcept { return x.v; }\n};\ntemplate <> struct std::hash {\n std::size_t operator()(Y) const { return 0; }\n};\ntemplate <> struct std::hash : std::hash { };\n\ntemplate constexpr bool is_hash_combinable = requires { jegp::hash_combine(std::declval()...); };\n\nconstexpr void test_hash_combine() {\n static_assert(not is_hash_combinable<>);\n static_assert(not is_hash_combinable);\n static_assert(not is_hash_combinable);\n static_assert(not is_hash_combinable);\n static_assert(not is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(is_hash_combinable);\n static_assert(not is_hash_combinable);\n static_assert(not is_hash_combinable);\n static_assert(not is_hash_combinable);\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 constexpr bool is_static_downcastable = requires {\n jegp::static_downcast(std::declval());\n};\n\ntemplate \n requires(\n std::is_same_v>and std::is_same_v> and\n not std::is_same_v and std::is_base_of_v)\nconstexpr void assert_is_static_downcastable() {\n auto ok = [](bool b) { return b == ExpectedToPass; };\n\n static_assert(ok(is_static_downcastable));\n static_assert(ok(is_static_downcastable));\n static_assert(ok(is_static_downcastable));\n static_assert(ok(is_static_downcastable));\n\n static_assert(not is_static_downcastable);\n static_assert(ok(is_static_downcastable));\n static_assert(not is_static_downcastable);\n static_assert(ok(is_static_downcastable));\n\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\n static_assert(ok(is_static_downcastable));\n static_assert(ok(is_static_downcastable));\n\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\n static_assert(ok(is_static_downcastable));\n\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\n static_assert(not is_static_downcastable);\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();\n assert_is_static_downcastable();\n assert_is_static_downcastable();\n assert_is_static_downcastable();\n}\n\nconsteval void test() {\n test_hash_combine();\n test_static_downcast();\n}\n\nint main() { test(); }\n<|endoftext|>"} {"text":"\/***************************************************************************\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 \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \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 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\nimei support\/***************************************************************************\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 \r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \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 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":"\/\/\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 \n#include \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 buffer);\n template\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\n tz::gl::Buffer* get(std::size_t idx);\n template\n const tz::gl::Buffer* get(std::size_t idx) const;\n private:\n void verify() const;\n\n ObjectHandle vao;\n std::vector> buffers;\n };\n\n namespace bound\n {\n int vao();\n }\n}\n\n#include \"gl\/object.inl\"\n#endif \/\/ TOPAZ_GL_OBJECT_HPP* Better documentation for tz::gl::Object!\/\/\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 \n#include \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 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\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\n tz::gl::Buffer* 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\n const tz::gl::Buffer* get(std::size_t idx) const;\n private:\n void verify() const;\n\n ObjectHandle vao;\n std::vector> 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":"\/\/ glfw_main.cpp\n\n#include \n\n#if defined(_WIN32)\n# include \n# define GLFW_EXPOSE_NATIVE_WIN32\n# define GLFW_EXPOSE_NATIVE_WGL\n#elif defined(__linux__)\n# include \n# include \n# define GLFW_EXPOSE_NATIVE_X11\n# define GLFW_EXPOSE_NATIVE_GLX\n#endif\n\n#include \n\n#if !defined(__APPLE__)\n# include \n#endif\n\n#include \n\n#include \n#include \n#include \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; iDraw rect to fill screen.\/\/ glfw_main.cpp\n\n#include \n\n#if defined(_WIN32)\n# include \n# define GLFW_EXPOSE_NATIVE_WIN32\n# define GLFW_EXPOSE_NATIVE_WGL\n#elif defined(__linux__)\n# include \n# include \n# define GLFW_EXPOSE_NATIVE_X11\n# define GLFW_EXPOSE_NATIVE_GLX\n#endif\n\n#include \n\n#if !defined(__APPLE__)\n# include \n#endif\n\n#include \n\n#include \n#include \n#include \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"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \"..\/include\/handle.h\"\n#include \"..\/include\/glshader.h\"\n#include \"..\/include\/glprogram.h\"\n\nconst std::function 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 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}\nglprogram.cpp doesn't need to include iostream>#include \n#include \n#include \n#include \n#include \n#include \"..\/include\/handle.h\"\n#include \"..\/include\/glshader.h\"\n#include \"..\/include\/glprogram.h\"\n\nconst std::function 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 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":"\/\/\/\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, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"FactorTableGourdon.hpp\"\n\n#include \n#include \n\nusing namespace std;\nusing namespace primecount;\n\nnamespace {\n\ntemplate \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(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(z);\n FactorTableGourdon 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::max())\n {\n auto primes = generate_primes(y);\n FactorTableGourdon 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(y);\n FactorTableGourdon 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\nBig speedup\/\/\/\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, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \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 \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 \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(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(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::max())\n {\n auto primes = generate_primes(y);\n c = C_OpenMP((intfast128_t) x, y, z, k, primes, threads);\n }\n else\n {\n auto primes = generate_primes(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":"\n#include \"input.h\"\n#include \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(\"\");\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 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\nrecognize keypad\n#include \"input.h\"\n#include \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(\"\");\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 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":"\/*\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\nUse UnitResource data to set poses of objects\/*\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":"#pragma once\n\n#include \n\n#include \"Runtime\/Collision\/CCollidableAABox.hpp\"\n#include \"Runtime\/World\/CActor.hpp\"\n\n#include \n#include \n#include \n#include \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 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& GetLastFloorPlaneNormal() const {\n return x228_lastFloorPlaneNormal;\n }\n void SetLastFloorPlaneNormal(const std::optional& 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\nCPhysicsActor: Add names to parameters in prototypes#pragma once\n\n#include \n\n#include \"Runtime\/Collision\/CCollidableAABox.hpp\"\n#include \"Runtime\/World\/CActor.hpp\"\n\n#include \n#include \n#include \n#include \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 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& GetLastFloorPlaneNormal() const {\n return x228_lastFloorPlaneNormal;\n }\n void SetLastFloorPlaneNormal(const std::optional& 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":"#include \n#include \n#include \n#include \n\n#include \"oglDisplay.h\"\n\n#include \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);add position to ini fix initial values#include \n#include \n#include \n#include \n\n#include \"oglDisplay.h\"\n\n#include \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":"\/\/\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 \n#include \n#include \n#include \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());\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 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 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 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 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}\ntestcam\/ufit full test looping over various combinations of grid locations\/\/\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 \n#include \n#include \n#include \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());\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 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 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 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;\n\n\t\/\/! Spots covering detector size\n\tstd::vector\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 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\n\tdetPairs\n\t\t( std::vector const & spots\n\t\t)\n\t{\n\t\tstd::vector 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 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 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 << \"\" << 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":"\n#ifdef _WIN32\n#include \n#else\n#include \n#include \n#include \n#endif\n\n#include \n#include \n#include \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 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 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::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::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, ¶m) != 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}\nError: Fixed Linux implementation of setErrorString\n#ifdef _WIN32\n#include \n#else\n#include \n#include \n#include \n#include \n#include \n#include \n#endif\n\n#include \n#include \n#include \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 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 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::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::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":"\/\/ Hex math taken from the amazing Amit Patel @ http:\/\/www.redblobgames.com\/grids\/hexagons\/\n\n#include \n#include \n#include \n#include \n#include \n#include \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; ymap.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; ymap.height; ++y)\n {\n for(int x=0; xmap.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; ymap.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}\nAdd initial basic acceleration\/braking implementation\/\/ Hex math taken from the amazing Amit Patel @ http:\/\/www.redblobgames.com\/grids\/hexagons\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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; ymap.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; ymap.height; ++y)\n {\n for(int x=0; xmap.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; ymap.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":"fix bad assertion<|endoftext|>"} {"text":"Adding stdlib to CsvFile<|endoftext|>"} {"text":"Bugfix for when last line is a comment<|endoftext|>"} {"text":"Fix illegal variable name<|endoftext|>"} {"text":"\/\/ Scintilla source code edit control\n\/** @file LexPS.cxx\n ** Lexer for PostScript\n **\n ** Written by Nigel Hathaway .\n ** The License.txt file describes the conditions under which this software may be distributed.\n **\/\n\n#include \n#include \n#include \n#include \n#include \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(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(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);\nPatch from Kein-Hong Man fixes a CRLF glitch in LexPS.\/\/ Scintilla source code edit control\n\/** @file LexPS.cxx\n ** Lexer for PostScript\n **\n ** Written by Nigel Hathaway .\n ** The License.txt file describes the conditions under which this software may be distributed.\n **\/\n\n#include \n#include \n#include \n#include \n#include \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(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(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":"#include \"Macro.h\"\n#include \"BlackCrow.h\"\n#include \"Planned.h\"\n#include \"Worker.h\"\n#include \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 = *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 Macro::planUnit(BWAPI::UnitType type, BWAPI::Position nearTo) {\n\t\tauto unit = std::make_shared(bc, type, nearTo);\n\t\tplannedStuff.push_back(unit);\n\t\treturn unit;\n\t}\n\n\tstd::shared_ptr Macro::planBuilding(BWAPI::UnitType type, BWAPI::TilePosition buildPosition) {\n\t\tauto building = std::make_shared(bc, type, buildPosition);\n\t\tplannedStuff.push_back(building);\n\t\treturn building;\n\t}\n\n\tstd::shared_ptr Macro::planExtractor(Geyser& geyser) {\n\t\tauto extractor = std::make_shared(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) { \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 = std::dynamic_pointer_cast(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 = std::dynamic_pointer_cast(planned);\n\t\t\tif (plannedUnit && plannedUnit->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr plannedBuilding = std::dynamic_pointer_cast(planned);\n\t\t\tif (plannedBuilding && plannedBuilding->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr plannedUpgrade = std::dynamic_pointer_cast(planned);\n\t\t\tif (plannedUpgrade && plannedUpgrade->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr plannedTech = std::dynamic_pointer_cast(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::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::max();\n\n\t\tBase* closestEstablishedWorkerNeeded = nullptr;\n\t\tdouble closestEstablishedWorkerNeededDistance = std::numeric_limits::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 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 : 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 Macro::getAllLarvae() {\n\t\tstd::vector 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 Macro::getReservedLarvae() {\n\t\tstd::vector reservedLarvae;\n\n\t\t\/\/ TODO this doesn't look good\n\t\tfor (std::shared_ptr planned : plannedStuff) {\n\t\t\tstd::shared_ptr pu = std::dynamic_pointer_cast(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 Macro::getUnreservedLarvae() {\n\t\tstd::vector allLarvae = getAllLarvae();\n\t\tstd::vector reservedLarvae = getReservedLarvae();\n\t\tstd::vector 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}Implemented getTotalLarvaeAmount()#include \"Macro.h\"\n#include \"BlackCrow.h\"\n#include \"Planned.h\"\n#include \"Worker.h\"\n#include \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 = *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 Macro::planUnit(BWAPI::UnitType type, BWAPI::Position nearTo) {\n\t\tauto unit = std::make_shared(bc, type, nearTo);\n\t\tplannedStuff.push_back(unit);\n\t\treturn unit;\n\t}\n\n\tstd::shared_ptr Macro::planBuilding(BWAPI::UnitType type, BWAPI::TilePosition buildPosition) {\n\t\tauto building = std::make_shared(bc, type, buildPosition);\n\t\tplannedStuff.push_back(building);\n\t\treturn building;\n\t}\n\n\tstd::shared_ptr Macro::planExtractor(Geyser& geyser) {\n\t\tauto extractor = std::make_shared(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) { \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 = std::dynamic_pointer_cast(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 = std::dynamic_pointer_cast(planned);\n\t\t\tif (plannedUnit && plannedUnit->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr plannedBuilding = std::dynamic_pointer_cast(planned);\n\t\t\tif (plannedBuilding && plannedBuilding->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr plannedUpgrade = std::dynamic_pointer_cast(planned);\n\t\t\tif (plannedUpgrade && plannedUpgrade->type == type)\n\t\t\t\treturn ++sum;\n\n\t\t\tstd::shared_ptr plannedTech = std::dynamic_pointer_cast(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::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::max();\n\n\t\tBase* closestEstablishedWorkerNeeded = nullptr;\n\t\tdouble closestEstablishedWorkerNeededDistance = std::numeric_limits::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 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 : 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 Macro::getAllLarvae() {\n\t\tstd::vector 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 Macro::getReservedLarvae() {\n\t\tstd::vector reservedLarvae;\n\n\t\t\/\/ TODO this doesn't look good\n\t\tfor (std::shared_ptr planned : plannedStuff) {\n\t\t\tstd::shared_ptr pu = std::dynamic_pointer_cast(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 Macro::getUnreservedLarvae() {\n\t\tstd::vector allLarvae = getAllLarvae();\n\t\tstd::vector reservedLarvae = getReservedLarvae();\n\t\tstd::vector 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":"prepare: remove also calls to __VERIFIER_assert in RemoveErrorCalls pass<|endoftext|>"} {"text":"#include \"stdafx.h\"\r\n#include \"model.h\"\r\n\r\nModel::Model(DeviceResources* resources)\r\n{\r\n\tm_pDeviceResources = shared_ptr(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();\r\n\tauto modelIndexes = new vector();\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(x),\r\n\t\tstatic_cast(y),\r\n\t\tstatic_cast(z),\r\n\t\tstatic_cast(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 materialstill dont know#include \"stdafx.h\"\r\n#include \"model.h\"\r\n\r\nModel::Model(DeviceResources* resources)\r\n{\r\n\tm_pDeviceResources = shared_ptr(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();\r\n\tauto modelIndexes = new vector();\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(x),\r\n\t\tstatic_cast(y),\r\n\t\tstatic_cast(z),\r\n\t\tstatic_cast(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":"\/*\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& images, vector& 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& 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\nadd note for CenterPointLayer.cpp\/*\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& images, vector& 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& 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":"#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 \n#include \n#include \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\n class Dynamic_Conversion_Impl : public Dynamic_Conversion\n {\n public:\n Dynamic_Conversion_Impl()\n : Dynamic_Conversion(user_type(), user_type())\n {\n }\n\n virtual Boxed_Value convert(const Boxed_Value &derived)\n {\n if (derived.get_type_info().bare_equal(user_type()))\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 data \n = boost::dynamic_pointer_cast(detail::Cast_Helper >::cast(derived));\n if (!data)\n {\n throw std::bad_cast();\n }\n\n return Boxed_Value(data);\n } else {\n boost::shared_ptr data \n = boost::dynamic_pointer_cast(detail::Cast_Helper >::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::cast(derived);\n const Base &data = dynamic_cast(d);\n return Boxed_Value(boost::cref(data));\n } else {\n Derived &d = detail::Cast_Helper::cast(derived);\n Base &data = dynamic_cast(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\n void add_conversion()\n {\n#ifndef CHAISCRIPT_NO_THREADS\n boost::unique_lock l(m_mutex);\n#endif\n\n m_conversions.push_back(\n boost::shared_ptr(new Dynamic_Conversion_Impl())\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 l(m_mutex);\n#endif\n\n for (std::vector >::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 get_conversion(const Type_Info &base, const Type_Info &derived)\n {\n#ifndef CHAISCRIPT_NO_THREADS\n boost::shared_lock l(m_mutex);\n#endif\n\n for (std::vector >::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 > m_conversions;\n };\n }\n\n template\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::value));\n BOOST_STATIC_ASSERT(boost::is_polymorphic::value);\n BOOST_STATIC_ASSERT(boost::is_polymorphic::value);\n\n detail::Dynamic_Conversions::get().add_conversion();\n }\n\n template\n bool dynamic_cast_converts()\n {\n return dynamic_cast_converts(user_type(), user_type());\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\n Boxed_Value boxed_dynamic_cast(const Boxed_Value &derived)\n {\n try {\n return detail::Dynamic_Conversions::get().get_conversion(user_type(), 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\nMake sure the same base\/derived relationship is never registered more than once#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 \n#include \n#include \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\n class Dynamic_Conversion_Impl : public Dynamic_Conversion\n {\n public:\n Dynamic_Conversion_Impl()\n : Dynamic_Conversion(user_type(), user_type())\n {\n }\n\n virtual Boxed_Value convert(const Boxed_Value &derived)\n {\n if (derived.get_type_info().bare_equal(user_type()))\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 data \n = boost::dynamic_pointer_cast(detail::Cast_Helper >::cast(derived));\n if (!data)\n {\n throw std::bad_cast();\n }\n\n return Boxed_Value(data);\n } else {\n boost::shared_ptr data \n = boost::dynamic_pointer_cast(detail::Cast_Helper >::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::cast(derived);\n const Base &data = dynamic_cast(d);\n return Boxed_Value(boost::cref(data));\n } else {\n Derived &d = detail::Cast_Helper::cast(derived);\n Base &data = dynamic_cast(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\n void add_conversion()\n {\n#ifndef CHAISCRIPT_NO_THREADS\n boost::unique_lock l(m_mutex);\n#endif\n\n if (find(user_type(), user_type()) == m_conversions.end())\n {\n m_conversions.push_back(\n boost::shared_ptr(new Dynamic_Conversion_Impl())\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 l(m_mutex);\n#endif\n\n return find(base, derived) != m_conversions.end();\n }\n\n\n boost::shared_ptr get_conversion(const Type_Info &base, const Type_Info &derived)\n {\n#ifndef CHAISCRIPT_NO_THREADS\n boost::shared_lock l(m_mutex);\n#endif\n\n std::vector >::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 >::const_iterator find(\n const Type_Info &base, const Type_Info &derived)\n {\n for (std::vector >::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 > m_conversions;\n };\n }\n\n template\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::value));\n BOOST_STATIC_ASSERT(boost::is_polymorphic::value);\n BOOST_STATIC_ASSERT(boost::is_polymorphic::value);\n\n detail::Dynamic_Conversions::get().add_conversion();\n }\n\n template\n bool dynamic_cast_converts()\n {\n return dynamic_cast_converts(user_type(), user_type());\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\n Boxed_Value boxed_dynamic_cast(const Boxed_Value &derived)\n {\n try {\n return detail::Dynamic_Conversions::get().get_conversion(user_type(), 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":"Change C-style array to the class array<|endoftext|>"} {"text":"#include \"Effect.h\"\n#include \n#include \n#include \n#include \"Compiler.h\"\n#include \"Ship.h\"\n#include \"Module.h\"\n#include \n#include \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 \n#include \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 > reusableEffects;\n\nboost::shared_ptr Effect::getEffect(Engine* engine, int effectID)\n{\n\tEngine::ScopedLock lock(*engine);\n\n\tstd::map >::iterator i, end = reusableEffects.end();\n\ti = reusableEffects.find(effectID);\n\tif (i == end) {\n\t\tboost::shared_ptr effect(new Effect(engine, effectID));\n\t\treusableEffects[effectID] = boost::weak_ptr(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 result = engine_->getSqlConnector()->exec(sql.str().c_str());\t\n\n\tif (result->next())\n\t{\n\t\tcategory_ = static_cast(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(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\nCleanup#include \"Effect.h\"\n#include \n#include \n#include \n#include \"Compiler.h\"\n#include \"Ship.h\"\n#include \"Module.h\"\n#include \n#include \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 \n#include \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 > reusableEffects;\n\nboost::shared_ptr Effect::getEffect(Engine* engine, int effectID)\n{\n\tEngine::ScopedLock lock(*engine);\n\n\tstd::map >::iterator i, end = reusableEffects.end();\n\ti = reusableEffects.find(effectID);\n\tif (i == end) {\n\t\tboost::shared_ptr effect(new Effect(engine, effectID));\n\t\treusableEffects[effectID] = boost::weak_ptr(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 result = engine_->getSqlConnector()->exec(sql.str().c_str());\t\n\n\tif (result->next())\n\t{\n\t\tcategory_ = static_cast(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(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":"\/*\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 \n#include \n#include \n#include \n\n\/\/ Instantiations of specific point types\nPCL_INSTANTIATE(MinCutSegmentation, PCL_XYZ_POINT_TYPES)Fix: include only if boost version > 1.39.99\/*\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 \n#if BOOST_VERSION > 103999\n\n#include \n#include \n#include \n#include \n\n\/\/ Instantiations of specific point types\nPCL_INSTANTIATE(MinCutSegmentation, PCL_XYZ_POINT_TYPES)\n\n#endif\n<|endoftext|>"} {"text":"\/*\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}\nFix for software skin renderer bug when rendering m_animate=false, need to init bone mat to identity\/*\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":"#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(\"image\");\n\n\tint nWindowSize = data.getParam(\"windowSize\",-1);\n\tdouble dSigma = data.getParam(\"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 input = {\n\t\t{\"image\", DataDescription(MATRIX, \"the image to apply the filter on.\") }\n\t};\n\tmap output = {\n\t\t{\"image\", DataDescription(MATRIX, \"the result image.\") }\n\t};\n\tmap 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\nadded comments to Gaussian module#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(\"windowSize\",-1);\n\tdouble dSigma = data.getParam(\"sigma\",0.0);\n\n\t\/\/ get a pointer to the \"image\" input data\n\tconst Matrix::ptr oMatrix = data.getInputData(\"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 input = {\n\t\t{\"image\", DataDescription(MATRIX, \"the image to apply the filter on.\") }\n\t};\n\tmap output = {\n\t\t{\"image\", DataDescription(MATRIX, \"the result image.\") }\n\t};\n\tmap 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":"\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nvoid show_usage()\n{\n \/\/ FIXME: Use arg[0] as program name?\n std::cerr << \"usage: evmcc (-b|-c|-d)+ \\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(ifs)),\n\t\t (std::istreambuf_iterator()));\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}\nminor changes in the compiler driver\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nvoid show_usage()\n{\n \/\/ FIXME: Use arg[0] as program name?\n std::cerr << \"usage: evmcc (-b|-c|-d)+ \\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(ifs)),\n\t\t (std::istreambuf_iterator()));\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":"\/*\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 \n#include \n#include \n#include \n#include \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 \nclass AddrRangeMap\n{\n private:\n typedef std::map 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 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 cond) const\n {\n return const_cast(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 cache;\n};\n\n#endif \/\/__BASE_ADDR_RANGE_MAP_HH__\nbase: Tag API methods and variables in addr_range_map.hh\/*\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 \n#include \n#include \n#include \n#include \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 \nclass AddrRangeMap\n{\n private:\n typedef std::map 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 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 cond) const\n {\n return const_cast(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 cache;\n};\n\n#endif \/\/__BASE_ADDR_RANGE_MAP_HH__\n<|endoftext|>"} {"text":"\/* 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 \n#include \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}\nFix for bug #9808\/* 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 \n#include \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":"\/* 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 \n#include \n#include \n#ifndef __WIN__\n#include \n#endif\n#include \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 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)\/* 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 \n#include \n#include \n#ifndef __WIN__\n#include \n#endif\n#include \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":"#include \"text.hpp\"\n#include \"..\/data\/data_library.hpp\"\n#include \"..\/utility\/error.hpp\"\n#include \"..\/json\/json.hpp\"\n\n#include \n\n#include \n#include \n#include \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 TextSourceParser::parse(const string & line)\n{\n vector 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 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 data_size { int(record_count) };\n auto dataset = make_shared(\"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 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 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(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\nIO \/ Text Package: Fix data source name#include \"text.hpp\"\n#include \"..\/data\/data_library.hpp\"\n#include \"..\/utility\/error.hpp\"\n#include \"..\/json\/json.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \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 TextSourceParser::parse(const string & line)\n{\n vector 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 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 data_size { int(record_count) };\n auto dataset = make_shared(\"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 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 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(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":"#include \"WPILib.h\"\n#include \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);\nadded Arrowbots logo#include \"WPILib.h\"\n#include \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":"\/\/ 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 \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 config;\n\tstd::unique_ptr dispatcher;\n\tstd::unique_ptr broadphase;\n\tstd::unique_ptr solver;\n\tstd::unique_ptr dynamicsWorld;\n};\n\nBulletPhysicsSystem::BulletPhysicsSystem() {\n\t_data = new Data;\n\t_data->config = std::make_unique();\n\t_data->dispatcher = std::make_unique(_data->config.get());\n\t_data->broadphase = std::make_unique();\n\t_data->solver = std::make_unique();\n\t_data->dynamicsWorld = std::make_unique(_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(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(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().get()))\n\t\t\tlifeComponent = eB->getComponent().get();\n\t\telse if ((bulletComponent = eB->getComponent().get()))\n\t\t\tlifeComponent = eA->getComponent().get();\n\n\t\tplayerComponent = eA->getComponent().get();\n\t\tif (!playerComponent)\n\t\t\tplayerComponent = eB->getComponent().get();\n\n\t\tif ((pickupComponent = eA->getComponent().get()))\n\t\t\tperkComponent = eB->getComponent().get();\n\t\telse if ((pickupComponent = eB->getComponent().get()))\n\t\t\tperkComponent = eA->getComponent().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()->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()->loadMesh(\"PARTICLEQUAD\");\n\n\tauto pETC = pE->addComponent();\n\tpETC->position = pos;\n\n\tauto pEPC = pE->addComponent();\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();\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();\n\ttransC->setPosition(pos);\n\ttransC->setScale(glm::vec3(10));\n\ttextEntity->addComponent()->loadMesh(\"TEXTQUAD\");\n\tauto lifeC = textEntity->addComponent();\n\tlifeC->health = lifeC->maxHP = 2;\n\tauto textC = textEntity->addComponent();\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 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() {}\nsubstr fix\/\/ 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 \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 config;\n\tstd::unique_ptr dispatcher;\n\tstd::unique_ptr broadphase;\n\tstd::unique_ptr solver;\n\tstd::unique_ptr dynamicsWorld;\n};\n\nBulletPhysicsSystem::BulletPhysicsSystem() {\n\t_data = new Data;\n\t_data->config = std::make_unique();\n\t_data->dispatcher = std::make_unique(_data->config.get());\n\t_data->broadphase = std::make_unique();\n\t_data->solver = std::make_unique();\n\t_data->dynamicsWorld = std::make_unique(_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(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(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().get()))\n\t\t\tlifeComponent = eB->getComponent().get();\n\t\telse if ((bulletComponent = eB->getComponent().get()))\n\t\t\tlifeComponent = eA->getComponent().get();\n\n\t\tplayerComponent = eA->getComponent().get();\n\t\tif (!playerComponent)\n\t\t\tplayerComponent = eB->getComponent().get();\n\n\t\tif ((pickupComponent = eA->getComponent().get()))\n\t\t\tperkComponent = eB->getComponent().get();\n\t\telse if ((pickupComponent = eB->getComponent().get()))\n\t\t\tperkComponent = eA->getComponent().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()->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()->loadMesh(\"PARTICLEQUAD\");\n\n\tauto pETC = pE->addComponent();\n\tpETC->position = pos;\n\n\tauto pEPC = pE->addComponent();\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();\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();\n\ttransC->setPosition(pos);\n\ttransC->setScale(glm::vec3(10));\n\ttextEntity->addComponent()->loadMesh(\"TEXTQUAD\");\n\tauto lifeC = textEntity->addComponent();\n\tlifeC->health = lifeC->maxHP = 2;\n\tauto textC = textEntity->addComponent();\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 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":"\/\/ 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; iUpdate();\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; iUpdate();\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\nChanged MRI volume linear interpolator to nearest neighbour.\/\/ 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; iUpdate();\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; iUpdate();\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":"#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 \n\nusing DataType = double;\nusing VertexType = unsigned;\nusing Simplex = aleph::topology::Simplex;\nusing SimplicialComplex = aleph::topology::SimplicialComplex;\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}\nStarted documenting PLY example\/*\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 \n#include \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;\n using SimplicialComplex = aleph::topology::SimplicialComplex;\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":"\/\/\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 \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}\nClear full row.\/\/\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 \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":"\/*\n * Copyright (c) 2010 Peter Zotov \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 \n#include \n#include \n#include \n#include \n#include \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 \",\n \" flash_write|fw \",\n \" eeprom_read|er \",\n \" eeprom_write|ew \",\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] << \" [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}\nReviewed error classes.\/*\n * Copyright (c) 2010 Peter Zotov \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 \n#include \n#include \n#include \n#include \n#include \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 \",\n \" flash_write|fw \",\n \" eeprom_read|er \",\n \" eeprom_write|ew \",\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] << \" [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":"Express RefinementState as text rather than numeric codes when printing Elem info<|endoftext|>"} {"text":"\/*************************************************************************\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 \n#endif\n\n#include \"globals.hxx\"\n\n\/\/--> TRA\n#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_\n#include \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}\nINTEGRATION: CWS ooo19126 (1.7.176); FILE MERGED 2005\/09\/05 18:48:16 rt 1.7.176.1: #i54170# Change license header: remove SISSL\/*************************************************************************\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 \n#endif\n\n#include \"globals.hxx\"\n\n\/\/--> TRA\n#ifndef _COM_SUN_STAR_DATATRANSFER_XTRANSFERABLE_HPP_\n#include \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":"\/\/ 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 \/\/ rand()\n#include \n\n#include \n#include \n#include \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(\" @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(\" @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(\" @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(\" @write: %u bytes written\\n\", n);\n });\n });\n\n }).onDisconnect(\n [] (auto conn, auto reason) {\n printf(\" @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(\" TCP STATUS:\\n\\t%s\\n\", inet1->tcp().status().c_str());\n printf(\" 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 << \"\"\n << \"\"\n << \"<\/head>\"\n << \"

\"\n << \"Include<\/span>OS<\/span><\/h1>\"\n << \"

Now speaks TCP!<\/h2>\"\n \/\/ .... generate more dynamic content\n << \"

...and can improvise http. With limitations of course, but it's been easier than expected so far <\/p>\"\n << \"

© 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}\nTightened up newlines in output\/\/ 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 \/\/ rand()\n#include \n\n#include \n#include \n#include \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(\" @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(\" @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(\" @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(\" @write: %u bytes written\\n\", n);\n });\n });\n\n }).onDisconnect(\n [] (auto conn, auto reason) {\n printf(\" @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(\" TCP STATUS:\\n\\t%s\\n\", inet1->tcp().status().c_str());\n printf(\" 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 << \"\"\n << \"\"\n << \"<\/head>\"\n << \"

\"\n << \"Include<\/span>OS<\/span><\/h1>\"\n << \"

Now speaks TCP!<\/h2>\"\n \/\/ .... generate more dynamic content\n << \"

...and can improvise http. With limitations of course, but it's been easier than expected so far <\/p>\"\n << \"

© 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":"\/*\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 \n#include \n#include \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\nstruct ArrayOp : csnd::Plugin<1, 1> {\n int init() {\n csnd::Vector &out = outargs.vector_data(0);\n csnd::Vector &in = inargs.vector_data(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 &out = outargs.vector_data(0);\n csnd::Vector &in = inargs.vector_data(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>(csound, \"ceil\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"ceil\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"floor\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"floor\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"round\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"round\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"int\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"int\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"frac\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"frac\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"powoftwo\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"powoftwo\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"abs\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"abs\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"abs\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"abs\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log2\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log2\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log10\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log10\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"exp\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"exp\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"sqrt\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"sqrt\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"cos\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"cos\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"sin\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"sin\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"tan\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"tan\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"cosinv\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"cosinv\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"sininv\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"sininv\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"taninv\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"taninv\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"cosh\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"cosh\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"sinh\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"sinh\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"tanh\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(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}\nbinops for arrays\/*\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 \n#include \n#include \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\nstruct ArrayOp : csnd::Plugin<1, 1> {\n int init() {\n csnd::Vector &out = outargs.vector_data(0);\n csnd::Vector &in = inargs.vector_data(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 &out = outargs.vector_data(0);\n csnd::Vector &in = inargs.vector_data(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\nstruct ArrayOp2 : csnd::Plugin<1, 2> {\n int init() {\n csnd::Vector &out = outargs.vector_data(0);\n csnd::Vector &in1 = inargs.vector_data(0);\n csnd::Vector &in2 = inargs.vector_data(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 &out = outargs.vector_data(0);\n csnd::Vector &in1 = inargs.vector_data(0);\n csnd::Vector &in2 = inargs.vector_data(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>(csound, \"ceil\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"ceil\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"floor\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"floor\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"round\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"round\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"int\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"int\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"frac\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"frac\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"powoftwo\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"powoftwo\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"abs\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"abs\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"abs\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"abs\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log2\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log2\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log10\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log10\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"log\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"exp\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"exp\", \"k[]\", \"k[]\", csnd::thread::i);\n csnd::plugin>(csound, \"sqrt\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"sqrt\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"cos\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"cos\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"sin\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"sin\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"tan\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"tan\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"cosinv\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"cosinv\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"sininv\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"sininv\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"taninv\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"taninv\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"cosh\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"cosh\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"sinh\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"sinh\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"tanh\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"tanh\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"cbrt\", \"i[]\", \"i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"cbrt\", \"k[]\", \"k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"taninv\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"taninv\", \"k[]\", \"k[]k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"pow\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"pow\", \"k[]\", \"k[]k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"hypot\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"hypot\", \"k[]\", \"k[]k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"fmod\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"fmod\", \"k[]\", \"k[]k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"fmax\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n csnd::plugin>(csound, \"fmax\", \"k[]\", \"k[]k[]\", csnd::thread::ik);\n csnd::plugin>(csound, \"fmin\", \"i[]\", \"i[]i[]\", csnd::thread::i);\n csnd::plugin>(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":"#include \"Product.h\"\n#include \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::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(\"\");\n\n Wait();\n\n\tfor (std::vector::const_iterator i = iSourceList.begin(); i != iSourceList.end(); ++i) {\n iSourceXml.Append(\"\");\n\n \/\/TODO: Xml escape the name\n iSourceXml.Append(\"\");\n iSourceXml.Append((*i)->iName);\n iSourceXml.Append(\"<\/Name>\");\n\n iSourceXml.Append(\"\");\n iSourceXml.Append((*i)->iType);\n iSourceXml.Append(\"<\/Type>\");\n\n iSourceXml.Append(\"\");\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\nMinor changes to string manipulation#include \"Product.h\"\n#include \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::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(\"\");\n\n Wait();\n\n\tfor (std::vector::const_iterator i = iSourceList.begin(); i != iSourceList.end(); ++i) {\n iSourceXml.Append(\"\");\n\n \/\/TODO: Xml escape the name\n iSourceXml.Append(\"\");\n iSourceXml.Append((*i)->iName);\n iSourceXml.Append(\"<\/Name>\");\n\n iSourceXml.Append(\"\");\n iSourceXml.Append((*i)->iType);\n iSourceXml.Append(\"<\/Type>\");\n\n iSourceXml.Append(\"\");\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":"#include \"ScriptedGraphosGame.h\"\n\nint main()\n{\n\tGraphos::Core::ScriptedGraphosGame game;\n\n\tgame.Run();\n}Removed old Main.cpp<|endoftext|>"} {"text":"Check Point<|endoftext|>"} {"text":"\/\/\n\/\/ Alert system\n\/\/\n\n#include \n#include \n#include \n#include \n#include \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 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()));\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::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::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::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}\nChange keys for checkpointing\/\/\n\/\/ Alert system\n\/\/\n\n#include \n#include \n#include \n#include \n#include \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 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()));\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::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::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::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":"\/\/\n\/\/ Alert system\n\/\/\n\n#include \n#include \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 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()));\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::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::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::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}\nGive testnet it's own alert key.\/\/\n\/\/ Alert system\n\/\/\n\n#include \n#include \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 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()));\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::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::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::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":"#include \"AllocSlab.h\"\n#include \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}\nMinor type fix in alloc#include \"AllocSlab.h\"\n#include \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":"\/\/\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 \n#include \n#include \n#include \n\n#include \n#include \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 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\nBug fix. Keep a hold on socketfd until the Client is destroyed.\/\/\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 \n#include \n#include \n#include \n\n#include \n#include \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 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":"\/\/ 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();\n if (!method) {\n DVLOG(0) << \"Not resolved \" << *ast_method;\n return;\n }\n function_ = factory()->NewFunction(\n type_mapper()->Map(method->signature())->as());\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();\n DCHECK(callee) << \"Unresolved call\" << *node;\n auto const callee_type =\n MapType(callee->signature())->as();\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(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\nelang\/compiler\/cg: Make |CodeGenerator| not to process unreachable statement.\/\/ 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();\n if (!method) {\n DVLOG(0) << \"Not resolved \" << *ast_method;\n return;\n }\n function_ = factory()->NewFunction(\n type_mapper()->Map(method->signature())->as());\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();\n DCHECK(callee) << \"Unresolved call\" << *node;\n auto const callee_type =\n MapType(callee->signature())->as();\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(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":"#include \"QuickItemPainter.h\"\n\n#include \n#include \n#include \n#include \n#include \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();\n const QObject* border = _item->property(\"border\").value();\n const qreal border_width = border->property(\"width\").value();\n const QColor border_color = border->property(\"color\").value();\n const qreal radius = _item->property(\"radius\").value();\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();\n const QString text = _item->property(\"text\").value();\n const QColor color = _item->property(\"color\").value();\n const int wrapMode = _item->property(\"wrapMode\").value();\n int textFormat = _item->property(\"textFormat\").value();\n const int horizontalAlignment = _item->property(\"horizontalAlignment\").value();\n const int verticalAlignment = _item->property(\"verticalAlignment\").value();\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 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();\n const int fillMode = _item->property(\"fillMode\").value();\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}\nprint children in function of their z-order#include \"QuickItemPainter.h\"\n\n#include \n#include \n#include \n#include \n#include \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();\n const QObject* border = _item->property(\"border\").value();\n const qreal border_width = border->property(\"width\").value();\n const QColor border_color = border->property(\"color\").value();\n const qreal radius = _item->property(\"radius\").value();\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();\n const QString text = _item->property(\"text\").value();\n const QColor color = _item->property(\"color\").value();\n const int wrapMode = _item->property(\"wrapMode\").value();\n int textFormat = _item->property(\"textFormat\").value();\n const int horizontalAlignment = _item->property(\"horizontalAlignment\").value();\n const int verticalAlignment = _item->property(\"verticalAlignment\").value();\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 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();\n const int fillMode = _item->property(\"fillMode\").value();\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 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":"\/*\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 \n#include \n\n#if defined (TARGET_OS_MACOSX)\n#include \n#include \n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_NDSFIRMWARE)\n#include \n#include \n#elif defined (TARGET_OS_WINDOWS)\n#include \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}\nstopwatch: fix incorrect reference to m_timebase\/*\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 \n#include \n\n#if defined (TARGET_OS_MACOSX)\n#include \n#include \n#elif defined (TARGET_OS_LINUX) || defined (TARGET_OS_NDSFIRMWARE)\n#include \n#include \n#elif defined (TARGET_OS_WINDOWS)\n#include \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":"#include \n#include \n#include \n\n#include \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(0,vertexdata);\n vdescriptor.addAttribute(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 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 - Add legacy support#include \n#include \n#include \n\n#include \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(0,vertexdata);\n vdescriptor.addAttribute(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& 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 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":"Expose option to force the sync history type when opening a realm (#966)<|endoftext|>"} {"text":"#ifndef BONJOUR_DNSD_CALLBACK_FUNC_DEF_H__\n#define BONJOUR_DNSD_CALLBACK_FUNC_DEF_H__\n\n#include \n\n#include \n#include \n#include \n#include \n#include \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:..) \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__copy comment to callback func#ifndef BONJOUR_DNSD_CALLBACK_FUNC_DEF_H__\n#define BONJOUR_DNSD_CALLBACK_FUNC_DEF_H__\n\n#include \n\n#include \n#include \n#include \n#include \n#include \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 ...\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:..) \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":"\/\/===- 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 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}\nThread LLVMContext through MVT and related parts of SDISel.\/\/===- 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 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":"lb_http: use LbClusterConfig::sticky_mode<|endoftext|>"} {"text":"\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2008 Collabora Ltd. \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 \n#include \"TelepathyQt4\/Client\/_gen\/contact.moc.hpp\"\n\n#include \n#include \n#include \n#include \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 requestedFeatures;\n QSet 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::requestedFeatures() const\n{\n return mPriv->requestedFeatures;\n}\n\nQSet 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 self =\n mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n return mPriv->manager->requestContactsPresenceSubscription(\n QList >() << self,\n message);\n}\n\nPendingOperation *Contact::removePresenceSubscription(const QString &message)\n{\n QSharedPointer self =\n mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n return mPriv->manager->removeContactsPresenceSubscription(\n QList >() << self,\n message);\n}\n\nPendingOperation *Contact::authorizePresencePublication(const QString &message)\n{\n QSharedPointer self =\n mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n return mPriv->manager->authorizeContactsPresencePublication(\n QList >() << self,\n message);\n}\n\nPendingOperation *Contact::removePresencePublication(const QString &message)\n{\n QSharedPointer self =\n mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n return mPriv->manager->removeContactsPresencePublication(\n QList >() << 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 &requestedFeatures, const QVariantMap &attributes)\n : QObject(0), mPriv(new Private(manager, handle))\n{\n augment(requestedFeatures, attributes);\n}\n\nvoid Contact::augment(const QSet &requestedFeatures, const QVariantMap &attributes) {\n mPriv->requestedFeatures.unite(requestedFeatures);\n\n mPriv->id = qdbus_cast(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(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(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(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\nContact: Make sure subscription\/publishStateChanged is not emitted if nothing happened.\/*\n * This file is part of TelepathyQt4\n *\n * Copyright (C) 2008 Collabora Ltd. \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 \n#include \"TelepathyQt4\/Client\/_gen\/contact.moc.hpp\"\n\n#include \n#include \n#include \n#include \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 requestedFeatures;\n QSet 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::requestedFeatures() const\n{\n return mPriv->requestedFeatures;\n}\n\nQSet 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 self =\n mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n return mPriv->manager->requestContactsPresenceSubscription(\n QList >() << self,\n message);\n}\n\nPendingOperation *Contact::removePresenceSubscription(const QString &message)\n{\n QSharedPointer self =\n mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n return mPriv->manager->removeContactsPresenceSubscription(\n QList >() << self,\n message);\n}\n\nPendingOperation *Contact::authorizePresencePublication(const QString &message)\n{\n QSharedPointer self =\n mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n return mPriv->manager->authorizeContactsPresencePublication(\n QList >() << self,\n message);\n}\n\nPendingOperation *Contact::removePresencePublication(const QString &message)\n{\n QSharedPointer self =\n mPriv->manager->lookupContactByHandle(mPriv->handle[0]);\n return mPriv->manager->removeContactsPresencePublication(\n QList >() << 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 &requestedFeatures, const QVariantMap &attributes)\n : QObject(0), mPriv(new Private(manager, handle))\n{\n augment(requestedFeatures, attributes);\n}\n\nvoid Contact::augment(const QSet &requestedFeatures, const QVariantMap &attributes) {\n mPriv->requestedFeatures.unite(requestedFeatures);\n\n mPriv->id = qdbus_cast(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(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(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(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":"Remove qDebug from Issue #41<|endoftext|>"} {"text":"Backport crash fixes to Phantom::doExit from master<|endoftext|>"} {"text":"Add to CRC_List CRC-3\/GSM<|endoftext|>"} {"text":"two functions to read plates: fits and par<|endoftext|>"} {"text":"tls_wrap: move members to initialization list<|endoftext|>"} {"text":"fix potential crash when peers get disconnected when we announce pieces to them<|endoftext|>"} {"text":"#include \n#include \n#include \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 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}Enhanced code#include \n#include \n#include \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 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":"\/\/===-- 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\/\/ \/\/ 1 line, 32 or 64\n\/\/ \/\/ 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 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[asan] Fix line >80 chars.\/\/===-- 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\/\/ \/\/ 1 line, 32 or 64\n\/\/ \/\/ 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 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":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstack lv1;\nstack lv2;\nstack 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>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<update uoj2254#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstack lv1;\nstack lv2;\nstack 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>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<"} {"text":"\/\/ 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 \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);\nIncrease version to 1.0.2.6 r6\/\/ 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 \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":"\/*------------------------------------------------------------------------------\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::Ref eventContainer,\n Ptr::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::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::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::Ref timeLeft(new time_duration(*nextEventTime\n - *now));\n TimeConversion::sleep(timeLeft);\n nextEvent->start();\n } else if (imminent(now, nextEventEnd)) {\n Ptr::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::Ref start = TimeConversion::now();\n\n nextStep(start);\n\n \/\/ sleep until the next granularity\n Ptr::Ref end = TimeConversion::now();\n Ptr::Ref diff(new time_duration(*end - *start));\n if (*diff <= *granularity) {\n Ptr::Ref sleepTime(new time_duration(*granularity\n - *diff));\n TimeConversion::sleep(sleepTime);\n }\n }\n}\n\nminor sanity changes...\/*------------------------------------------------------------------------------\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::Ref eventContainer,\n Ptr::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::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::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::Ref timeLeft(new time_duration(*nextEventTime\n - *now));\n TimeConversion::sleep(timeLeft);\n nextEvent->start();\n } else if (imminent(now, nextEventEnd)) {\n Ptr::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::Ref start = TimeConversion::now();\n\n nextStep(start);\n\n \/\/ sleep until the next granularity\n Ptr::Ref end = TimeConversion::now();\n Ptr::Ref diff(new time_duration(*end - *start));\n if (*diff <= *granularity) {\n Ptr::Ref sleepTime(new time_duration(*granularity\n - *diff));\n TimeConversion::sleep(sleepTime);\n }\n }\n}\n\n<|endoftext|>"} {"text":"\/*\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* 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 dev(SkNEW_ARGS(SkDevice, (bm)));\n\n SkAutoTUnref 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\nSanitizing source files in Skia_Periodic_House_Keeping\/*\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* 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 dev(SkNEW_ARGS(SkDevice, (bm)));\n\n SkAutoTUnref 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":"\/******************************************************************************\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 \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(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(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(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(N));\n Proto->LogMagnitude = log(static_cast(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(Emalloc(N * sizeof(float)));\n Proto->Weight.Elliptical = static_cast(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(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(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}\nclusttool: Replace strtof by std::stringstream\/******************************************************************************\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 \/\/ for std::isnan\n#include \/\/ for std::locale::classic\n#include \/\/ 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(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(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(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(N));\n Proto->LogMagnitude = log(static_cast(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(Emalloc(N * sizeof(float)));\n Proto->Weight.Elliptical = static_cast(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(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(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":"\/*************************************************************************\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 \n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_\n#include \n#endif\n\n#ifndef _RTL_USTRING_H_\n#include \n#endif\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include \n#endif\n\n\nusing namespace ::com::sun::star;\n\n\nuno::Reference SAL_CALL EmbedServer_createInstance(\n const uno::Reference & xSMgr)\nthrow (uno::Exception)\n{\n uno::Reference 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\nINTEGRATION: CWS obo05 (1.4.8); FILE MERGED 2006\/08\/28 13:47:49 obo 1.4.8.1: #i53611# diable warnings C4917 and 4555\/*************************************************************************\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 \n#endif\n#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_REGISTRY_XREGISTRYKEY_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_REGISTRY_INVALIDREGISTRYEXCEPTION_HPP_\n#include \n#endif\n\n#ifndef _RTL_USTRING_H_\n#include \n#endif\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include \n#endif\n\n\nusing namespace ::com::sun::star;\n\n\nuno::Reference SAL_CALL EmbedServer_createInstance(\n const uno::Reference & xSMgr)\nthrow (uno::Exception)\n{\n uno::Reference 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":"#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(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(m_change);\n\n std::vector old_desktop_list;\n std::vector 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 to_make_invisible;\n std::vector 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::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::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 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::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_list;\n m_xmodel.get_icons(icon_list);\n\n for (std::vector::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}\nAdded location and size change handlers#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(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(m_change);\n\n std::vector old_desktop_list;\n std::vector 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 to_make_invisible;\n std::vector 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::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::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(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(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 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::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_list;\n m_xmodel.get_icons(icon_list);\n\n for (std::vector::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":"\/**\n * Copyright (c) 2015 - The CM Authors \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 \n#include \n#include \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 cm_logjoin_shutdown;\n\nvoid quit(int n) {\n cm_logjoin_shutdown = true;\n}\n\nstruct BackfillData {\n Option shop_name;\n Option shop_id;\n Option category1;\n Option category2;\n Option 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 \"\");\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 \"\");\n\n flags.defineFlag(\n \"batch_size\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"2048\",\n \"batch_size\",\n \"\");\n\n flags.defineFlag(\n \"worker_threads\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"4\",\n \"threads\",\n \"\");\n\n flags.defineFlag(\n \"upload_threads\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"1\",\n \"threads\",\n \"\");\n\n flags.defineFlag(\n \"no_dryrun\",\n fnord::cli::FlagParser::T_SWITCH,\n false,\n NULL,\n NULL,\n \"no dryrun\",\n \"\");\n\n flags.defineFlag(\n \"replica\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"replica id\",\n \"\");\n\n flags.defineFlag(\n \"no_dryrun\",\n fnord::cli::FlagParser::T_SWITCH,\n false,\n NULL,\n NULL,\n \"no dryrun\",\n \"\");\n\n flags.defineFlag(\n \"loglevel\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"\");\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 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\nconversion fix\/**\n * Copyright (c) 2015 - The CM Authors \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 \n#include \n#include \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 cm_logjoin_shutdown;\n\nvoid quit(int n) {\n cm_logjoin_shutdown = true;\n}\n\nstruct BackfillData {\n Option shop_name;\n Option shop_id;\n Option category1;\n Option category2;\n Option 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 \"\");\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 \"\");\n\n flags.defineFlag(\n \"batch_size\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"2048\",\n \"batch_size\",\n \"\");\n\n flags.defineFlag(\n \"worker_threads\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"4\",\n \"threads\",\n \"\");\n\n flags.defineFlag(\n \"upload_threads\",\n fnord::cli::FlagParser::T_INTEGER,\n false,\n NULL,\n \"1\",\n \"threads\",\n \"\");\n\n flags.defineFlag(\n \"no_dryrun\",\n fnord::cli::FlagParser::T_SWITCH,\n false,\n NULL,\n NULL,\n \"no dryrun\",\n \"\");\n\n flags.defineFlag(\n \"replica\",\n cli::FlagParser::T_STRING,\n true,\n NULL,\n NULL,\n \"replica id\",\n \"\");\n\n flags.defineFlag(\n \"no_dryrun\",\n fnord::cli::FlagParser::T_SWITCH,\n false,\n NULL,\n NULL,\n \"no dryrun\",\n \"\");\n\n flags.defineFlag(\n \"loglevel\",\n fnord::cli::FlagParser::T_STRING,\n false,\n NULL,\n \"INFO\",\n \"loglevel\",\n \"\");\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 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":"\/*=========================================================================\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 InputImageType;\n typedef otb::ImageFileReader ReaderType;\n typedef otb::List 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\nAjout test sur operator+ et operator- pour iterator\/*=========================================================================\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 InputImageType;\n typedef otb::ImageFileReader ReaderType;\n typedef otb::List 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":"#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 \n#include \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 >\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& 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 \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 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 >\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 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 \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;iRingBuffer: add oldest function#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 \n#include \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 >\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& 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 \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 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 >\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(const_cast*>(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(const_cast*>(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(const_cast*>(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(const_cast*>(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 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 \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"} {"text":"#include \n#include \"CUDADenseGraphBFSearcher.h\"\n#include \"Device.h\"\n\nusing namespace sqaod_cuda;\n\n\ntemplate\nvoid runBFSearcher() {\n typedef sq::MatrixType Matrix;\n\n Device device;\n device.initialize();\n \n int N = 100;\n CUDADenseGraphBFSearcher 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();\n runBFSearcher();\n}\nsetProblem() -> setQUBO().#include \n#include \"CUDADenseGraphBFSearcher.h\"\n#include \"Device.h\"\n\nusing namespace sqaod_cuda;\n\n\ntemplate\nvoid runBFSearcher() {\n typedef sq::MatrixType Matrix;\n\n Device device;\n device.initialize();\n \n int N = 100;\n CUDADenseGraphBFSearcher 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();\n runBFSearcher();\n}\n<|endoftext|>"} {"text":"\/\/ 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 \n#include \n#include \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(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(data);\n auto tuple = parser.cast(payload);\n auto iter = lv2_atom_tuple_begin(tuple);\n auto msg = parser.cast(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(atom));\n else if (m_parser.isSequence(atom))\n handleSequenceRequest(request, m_parser.cast(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(subjectAtom);\n const LV2_Atom_Object* body = m_parser.cast(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(targetAtom));\n Node* targetNode = m_nodes.lookup(targetId);\n BOOST_ASSERT_MSG( targetNode != nullptr, \"target node not found\" );\n\n Synth* targetSynth = dynamic_cast(targetNode);\n Group* targetGroup = targetSynth == nullptr ? dynamic_cast(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(pluginAtom);\n\n \/\/ get params from body\n\n \/\/ uris().methcla_plugin\n const std::shared_ptr 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(data)->m_env->process(numFrames, inputs, outputs);\n}\nRemove stale code\/\/ 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 \n#include \n#include \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(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(data);\n auto tuple = parser.cast(payload);\n auto iter = lv2_atom_tuple_begin(tuple);\n auto msg = parser.cast(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(atom));\n else if (m_parser.isSequence(atom))\n handleSequenceRequest(request, m_parser.cast(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(subjectAtom);\n const LV2_Atom_Object* body = m_parser.cast(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(targetAtom));\n Node* targetNode = m_nodes.lookup(targetId);\n BOOST_ASSERT_MSG( targetNode != nullptr, \"target node not found\" );\n\n Synth* targetSynth = dynamic_cast(targetNode);\n Group* targetGroup = targetSynth == nullptr ? dynamic_cast(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(pluginAtom);\n\n \/\/ get params from body\n\n \/\/ uris().methcla_plugin\n const std::shared_ptr 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(data)->m_env->process(numFrames, inputs, outputs);\n}\n<|endoftext|>"} {"text":"\/*\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\nbetter description for AllowEmptyGames\/*\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":"Set bar type as YErrorBar when creating InsertErrorBarsDialog.<|endoftext|>"} {"text":"\/**\n * @file libc.cpp\n * @author created by: Peter Hlavaty\n *\/\n\n#include \"libc.h\"\n#include \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(\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 inblock = std::unique_ptr(static_cast(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(DbgPrint(format, argptr));\n}\nvsnprintf fix\/**\n * @file libc.cpp\n * @author created by: Peter Hlavaty\n *\/\n\n#include \"libc.h\"\n#include \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(\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 inblock = std::unique_ptr(static_cast(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":"#include \"keytar.h\"\n\n#define UNICODE\n\n#include \n#include \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(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(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,\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(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\nBreak long line in src\/keytar_win.cc#include \"keytar.h\"\n\n#define UNICODE\n\n#include \n#include \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(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(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,\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(\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":"\/\/\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(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(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(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(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(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(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(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(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(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(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\nsrc: fixed a mistake\/\/\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(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(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(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(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(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(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(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(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(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(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":"Reduce indentation by early bailout.<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#pragma once\n#include \n#include \/\/ for std::move\nnamespace game\n{\n template struct Maybe_Owned;\n\n \/*!\n * Named to be consistent with make_shared and make_unique.\n *\/\n template \n Maybe_Owned make_maybe_owned(Args&&... args) noexcept\n {\n return Maybe_Owned(new T(std::forward(args)...), true);\n }\n \/*!\n * Named to contrast and stress the owned nature of the pointer passed in.\n *\/\n template \n Maybe_Owned make_owned_maybe(T* ptr) noexcept\n {\n return Maybe_Owned(ptr, true);\n }\n\n \/\/ TODO Support a custom deleter.\n template \n struct Maybe_Owned\n {\n template \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 \n Maybe_Owned(std::unique_ptr) noexcept;\n\n template \n Maybe_Owned(Maybe_Owned&&) noexcept;\n Maybe_Owned(Maybe_Owned const&) noexcept = delete;\n\n template \n Maybe_Owned& operator=(std::unique_ptr) noexcept;\n\n template \n Maybe_Owned& operator=(Maybe_Owned&&) 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 \n void set_pointer(Maybe_Owned const&) noexcept;\n\n template \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 \n template \n Maybe_Owned::Maybe_Owned(Args&&... args) noexcept\n : owned_(true), ptr_(new T{std::forward(args)...}) {}\n\n template \n Maybe_Owned::Maybe_Owned(T&& t) noexcept\n : owned_(true), ptr_(new T(std::move(t))) {}\n\n template \n Maybe_Owned::Maybe_Owned(T* t, bool o) noexcept : owned_(o), ptr_(t) {}\n\n template \n template \n Maybe_Owned::Maybe_Owned(std::unique_ptr ptr) noexcept\n : owned_(true), ptr_(ptr.release()) {}\n\n template \n Maybe_Owned::~Maybe_Owned() noexcept\n {\n if(owned_) delete ptr_;\n }\n\n template \n template \n Maybe_Owned::Maybe_Owned(Maybe_Owned&& 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 \n template \n Maybe_Owned& Maybe_Owned::operator=(std::unique_ptr ptr) noexcept\n {\n owned_ = true;\n ptr_ = ptr.release();\n\n return *this;\n }\n\n template \n template \n Maybe_Owned& Maybe_Owned::operator=(Maybe_Owned&& 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 \n void Maybe_Owned::set_owned(T&& t) noexcept\n {\n owned_ = true;\n ptr_ = new T(std::move(t));\n }\n template \n void Maybe_Owned::set_owned(T const& t) noexcept\n {\n owned_ = true;\n ptr_ = new T(t);\n }\n template \n void Maybe_Owned::set_owned(T* t) noexcept\n {\n owned_ = true;\n ptr_ = t;\n }\n template \n void Maybe_Owned::set_pointer(T* t, bool o) noexcept\n {\n owned_ = o;\n ptr_ = t;\n }\n template \n template \n void Maybe_Owned::set_pointer(Maybe_Owned const& mo) noexcept\n {\n set_pointer(mo.get(), false);\n }\n\n template \n template \n void Maybe_Owned::emplace_owned(Args&&... args) noexcept\n {\n owned_ = true;\n ptr_ = new R(std::forward(args)...);\n }\n\n template \n T* Maybe_Owned::get() const noexcept\n {\n return ptr_;\n }\n\n template \n T&& Maybe_Owned::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 \n T* Maybe_Owned::operator->() const noexcept\n {\n return ptr_;\n }\n template \n T& Maybe_Owned::operator*() const noexcept\n {\n return *ptr_;\n }\n\n template \n bool Maybe_Owned::is_owned() const noexcept\n {\n return owned_;\n }\n template \n bool Maybe_Owned::is_pointer() const noexcept\n {\n return !owned_;\n }\n\n template \n Maybe_Owned::operator bool() const noexcept\n {\n return get();\n }\n}\nMaybe_Owned now releases its own pointer (if owned) when switching pointers.\/*\n * Copyright (C) 2015 Luke San Antonio\n * All rights reserved.\n *\/\n#pragma once\n#include \n#include \/\/ for std::move\nnamespace game\n{\n template struct Maybe_Owned;\n\n \/*!\n * Named to be consistent with make_shared and make_unique.\n *\/\n template \n Maybe_Owned make_maybe_owned(Args&&... args) noexcept\n {\n return Maybe_Owned(new T(std::forward(args)...), true);\n }\n \/*!\n * Named to contrast and stress the owned nature of the pointer passed in.\n *\/\n template \n Maybe_Owned make_owned_maybe(T* ptr) noexcept\n {\n return Maybe_Owned(ptr, true);\n }\n\n \/\/ TODO Support a custom deleter.\n template \n struct Maybe_Owned\n {\n template \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 \n Maybe_Owned(std::unique_ptr) noexcept;\n\n template \n Maybe_Owned(Maybe_Owned&&) noexcept;\n Maybe_Owned(Maybe_Owned const&) noexcept = delete;\n\n template \n Maybe_Owned& operator=(std::unique_ptr) noexcept;\n\n template \n Maybe_Owned& operator=(Maybe_Owned&&) 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 \n void set_pointer(Maybe_Owned const&) noexcept;\n\n template \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 \n template \n Maybe_Owned::Maybe_Owned(Args&&... args) noexcept\n : owned_(true), ptr_(new T{std::forward(args)...}) {}\n\n template \n Maybe_Owned::Maybe_Owned(T&& t) noexcept\n : owned_(true), ptr_(new T(std::move(t))) {}\n\n template \n Maybe_Owned::Maybe_Owned(T* t, bool o) noexcept : owned_(o), ptr_(t) {}\n\n template \n template \n Maybe_Owned::Maybe_Owned(std::unique_ptr ptr) noexcept\n : owned_(true), ptr_(ptr.release()) {}\n\n template \n Maybe_Owned::~Maybe_Owned() noexcept\n {\n release();\n }\n\n template \n template \n Maybe_Owned::Maybe_Owned(Maybe_Owned&& 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 \n template \n Maybe_Owned& Maybe_Owned::operator=(std::unique_ptr ptr) noexcept\n {\n release();\n\n owned_ = true;\n ptr_ = ptr.release();\n\n return *this;\n }\n\n template \n template \n Maybe_Owned& Maybe_Owned::operator=(Maybe_Owned&& 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 \n void Maybe_Owned::set_owned(T&& t) noexcept\n {\n set_pointer(new T(std::move(t)), true);\n }\n template \n void Maybe_Owned::set_owned(T const& t) noexcept\n {\n set_pointer(new T(t), true);\n }\n template \n void Maybe_Owned::set_owned(T* t) noexcept\n {\n set_pointer(t, true);\n }\n template \n void Maybe_Owned::set_pointer(T* t, bool o) noexcept\n {\n *this = Maybe_Owned(t, o);\n }\n template \n template \n void Maybe_Owned::set_pointer(Maybe_Owned const& mo) noexcept\n {\n set_pointer(mo.get(), false);\n }\n\n template \n template \n void Maybe_Owned::emplace_owned(Args&&... args) noexcept\n {\n *this = make_maybe_owned(std::forward(args)...);\n }\n\n template \n T* Maybe_Owned::get() const noexcept\n {\n return ptr_;\n }\n\n template \n T&& Maybe_Owned::unwrap() noexcept\n {\n T&& old_t = std::move(*ptr_);\n release();\n return std::move(old_t);\n }\n\n template \n T* Maybe_Owned::operator->() const noexcept\n {\n return ptr_;\n }\n template \n T& Maybe_Owned::operator*() const noexcept\n {\n return *ptr_;\n }\n\n template \n bool Maybe_Owned::is_owned() const noexcept\n {\n return owned_;\n }\n template \n bool Maybe_Owned::is_pointer() const noexcept\n {\n return !owned_;\n }\n\n template \n Maybe_Owned::operator bool() const noexcept\n {\n return get();\n }\n template \n void Maybe_Owned::release() noexcept\n {\n if(owned_)\n {\n delete ptr_;\n }\n ptr_ = nullptr;\n owned_ = false;\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nnamespace thinkyoung {\n namespace client {\n namespace detail {\n \n thinkyoung::blockchain::TransactionIdType detail::ClientImpl::network_broadcast_transactions(const std::vector& 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 detail::ClientImpl::network_get_peer_info(bool hide_firewalled_nodes)const {\n std::vector results;\n std::vector 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& 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 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 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 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 ClientImpl::network_get_blocked_ips()const {\n return _p2p_node->get_blocked_ips();\n }\n \n }\n }\n} \/\/ namespace thinkyoung::client::detail\nDistinguish the transaction type,deal with the contract transaction#include \n#include \n#include \n\nnamespace thinkyoung {\n namespace client {\n namespace detail {\n \n thinkyoung::blockchain::TransactionIdType detail::ClientImpl::network_broadcast_transactions(const std::vector& 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 detail::ClientImpl::network_get_peer_info(bool hide_firewalled_nodes)const {\n std::vector results;\n std::vector 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& 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 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 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 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 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":"\/*************************************************************************\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 * \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 \n#include \n#include \n#include \n#include \n#include \n#include \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\/\/.............................................................................\nchart45: #i110805# Chartshapes: Toolbarbuttons can't be opened\/*************************************************************************\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 * \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 \n#include \n#include \n#include \n#include \n#include \n#include \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":"\/\/ Copyright 2015 FMAW\n\n#include \".\/player_ai.h\"\n\n#include \n#include \n#include \n#include \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 \n\nPlayerAI::PlayerAI(Grid *grid, std::function callback) :\n grid(grid),\n onFinishTurnCallback(callback),\n seed(42) {}\n\nPlayerAI::PlayerAI(Grid *grid, std::function 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 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 IAunits;\n std::vector IApaths;\n std::vector playerUnits;\n std::vector playerPaths;\n std::vector 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> IAUnitCanAttack;\n std::map> 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 shouldAttack;\n std::vector 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 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}\nReversed performance improvements to ensure stability.\/\/ Copyright 2015 FMAW\n\n#include \".\/player_ai.h\"\n\n#include \n#include \n#include \n#include \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 \n\nPlayerAI::PlayerAI(Grid *grid, std::function callback) :\n grid(grid),\n onFinishTurnCallback(callback),\n seed(42) {}\n\nPlayerAI::PlayerAI(Grid *grid, std::function 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 IAunits;\n std::vector IApaths;\n std::vector playerUnits;\n std::vector playerPaths;\n std::vector 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> IAUnitCanAttack;\n std::map> PlayerUnitCanBeAttackedBy;\n\n std::map> IAUnitsPossibleMovements;\n std::map 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 shouldAttack;\n std::vector 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 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":"#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 \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 \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 \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 \n\t\toperator Down const &() const\n\t\t{\n\t\t\tassert(m_base);\n\t\t\treturn dynamic_cast(*m_base);\n\t\t}\n\n\tprivate:\n\n\t\tBase const *m_base;\n\t};\n\n\ttemplate \n\tvoid check_expression(p0::expression_tree const &expression, Handler const &handler)\n\t{\n\t\thandler(down_caster(expression));\n\t}\n\n\ttemplate \n\tvoid check_statement(p0::statement_tree const &statement, Handler const &handler)\n\t{\n\t\thandler(down_caster(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}\ntest some expected parser errors#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 \n\n\nnamespace\n{\n\ttemplate \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 \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 \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 \n\t\toperator Down const &() const\n\t\t{\n\t\t\tassert(m_base);\n\t\t\treturn dynamic_cast(*m_base);\n\t\t}\n\n\tprivate:\n\n\t\tBase const *m_base;\n\t};\n\n\ttemplate \n\tvoid check_expression(p0::expression_tree const &expression, Handler const &handler)\n\t{\n\t\thandler(down_caster(expression));\n\t}\n\n\ttemplate \n\tvoid check_statement(p0::statement_tree const &statement, Handler const &handler)\n\t{\n\t\thandler(down_caster(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":"Update FTPClient.cpp<|endoftext|>"} {"text":"\/*\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 \n#include \n#include \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}\nImplementing Laby DirectionCheck().\/*\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 \n#include \n#include \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":"\/*\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(&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}\ndecrement lockcount if we failed to get pixels\/*\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(&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":"\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, fTileCount);\n}\n\nSkTileGrid::~SkTileGrid() {\n SkDELETE_ARRAY(fTileData);\n}\n\nSkTDArray& 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* 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 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*> storage(queryTileCount);\n SkTDArray** 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}\nImproving comment in SkTileGrid::search\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, fTileCount);\n}\n\nSkTileGrid::~SkTileGrid() {\n SkDELETE_ARRAY(fTileData);\n}\n\nSkTDArray& 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* 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 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*> storage(queryTileCount);\n SkTDArray** 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":"\/*\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 \n#include \n\n#include \n#include \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 \nUSE_UATX0();\n\n\/\/ Buffers for UART\nstatic const uint8_t OUTPUT_BUFFER_SIZE = 128;\nstatic char output_buffer[OUTPUT_BUFFER_SIZE];\nstatic UATX uatx{output_buffer};\nFormattedOutput trace = uatx.fout();\n#else\n#include \n#endif\n\n\/\/ Single port used by this circuit\nstatic constexpr const Board::Port PORT = FastPinType::PORT;\n\n\/\/ Check at compile time that all pins are on the same port\nstatic_assert(FastPinType::PORT == PORT, \"LATCH must be on same port as CLOCK\");\nstatic_assert(FastPinType::PORT == PORT, \"DATA must be on same port as CLOCK\");\nstatic_assert(FastPinType::MASK | FastPinType::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{ALL_DDR, ALL_PORT};\n\t\n\t\/\/ Initialize Multiplexer\n\tMULTIPLEXER mux;\n\t\n\tButton stop;\n\t\/\/ Step #1: Initialize board with 1st generation\n\t\/\/===============================================\n\t{\n\t\tButton select;\n\t\tAnalogInput row_input;\n\t\tAnalogInput 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}\nConway small code cleanup for ATtiny.\/*\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 \n#include \n\n#include \n#include \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 \nUSE_UATX0();\n\n\/\/ Buffers for UART\nstatic const uint8_t OUTPUT_BUFFER_SIZE = 128;\nstatic char output_buffer[OUTPUT_BUFFER_SIZE];\nstatic UATX uatx{output_buffer};\nFormattedOutput trace = uatx.fout();\n#endif\n\n\/\/ Single port used by this circuit\nstatic constexpr const Board::Port PORT = FastPinType::PORT;\n\n\/\/ Check at compile time that all pins are on the same port\nstatic_assert(FastPinType::PORT == PORT, \"LATCH must be on same port as CLOCK\");\nstatic_assert(FastPinType::PORT == PORT, \"DATA must be on same port as CLOCK\");\nstatic_assert(FastPinType::MASK | FastPinType::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{ALL_DDR, ALL_PORT};\n\t\n\t\/\/ Initialize Multiplexer\n\tMULTIPLEXER mux;\n\t\n\tButton stop;\n\t\/\/ Step #1: Initialize board with 1st generation\n\t\/\/===============================================\n\t{\n\t\tButton select;\n\t\tAnalogInput row_input;\n\t\tAnalogInput 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":"#include \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(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());\n n_jt.push_back(std::vector());\n dish_assignments_.push_back(std::vector());\n table_assignments_.push_back(std::vector(nterms(eid), 0));\n n_jtv.push_back(std::vector< std::map>());\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>\nmicroscopes::lda::state::word_distribution() {\n \/\/ Distribution over words for each topic\n std::vector> vec;\n vec.reserve(dishes_.size());\n for (auto k : dishes_) {\n if (k == 0) continue;\n vec.push_back(std::map());\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>\nmicroscopes::lda::state::document_distribution () {\n \/\/ Distribution over topics for each document\n std::vector> theta;\n theta.reserve(dish_assignments_.size());\n std::vector 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 &n_jt_ = n_jt[j];\n std::vector 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(p_jk);\n theta.push_back(p_jk);\n }\n return theta;\n}\n\ndouble\nmicroscopes::lda::state::perplexity() {\n std::vector> phi = word_distribution();\n std::vector> theta = document_distribution();\n phi.insert(phi.begin(), std::map());\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> 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(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(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(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());\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\nAllow for gaps in dish indices on explicit initialization#include \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(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());\n n_jt.push_back(std::vector());\n dish_assignments_.push_back(std::vector());\n table_assignments_.push_back(std::vector(nterms(eid), 0));\n n_jtv.push_back(std::vector< std::map>());\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>\nmicroscopes::lda::state::word_distribution() {\n \/\/ Distribution over words for each topic\n std::vector> vec;\n vec.reserve(dishes_.size());\n for (auto k : dishes_) {\n if (k == 0) continue;\n vec.push_back(std::map());\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>\nmicroscopes::lda::state::document_distribution () {\n \/\/ Distribution over topics for each document\n std::vector> theta;\n theta.reserve(dish_assignments_.size());\n std::vector 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 &n_jt_ = n_jt[j];\n std::vector 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(p_jk);\n theta.push_back(p_jk);\n }\n return theta;\n}\n\ndouble\nmicroscopes::lda::state::perplexity() {\n std::vector> phi = word_distribution();\n std::vector> theta = document_distribution();\n phi.insert(phi.begin(), std::map());\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> 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(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(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(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());\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":"#include \"KEngine\/Common\/StopWatch.hpp\"\n#include \"KEngine\/Core\/EventManagerImpl.hpp\"\n#include \"KEngine\/Log\/Log.hpp\"\n\n#include \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}\nrenamed parameter#include \"KEngine\/Common\/StopWatch.hpp\"\n#include \"KEngine\/Core\/EventManagerImpl.hpp\"\n#include \"KEngine\/Log\/Log.hpp\"\n\n#include \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":"#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"timestamp.h\"\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -- Helper Functions\n\/\/ -----------------------------------------------------------------------------\ntemplate \nT sqrt_int(T num) {\n return static_cast(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();\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();\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(\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 \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\nfixed indent#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"timestamp.h\"\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -- Helper Functions\n\/\/ -----------------------------------------------------------------------------\ntemplate \nT sqrt_int(T num) {\n return static_cast(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();\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();\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(\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 \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":"\/\/ 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\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 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\nVSX tconfig logic\/\/ 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\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 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":"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\"<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}\nimproved title of x-axisusing 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\"<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":"#pragma once\n\n#include \n#include \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\nRegister the new fonts#pragma once\n\n#include \n#include \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":"#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- Fix issue 9.#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":"#include \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::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::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::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::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(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}\nDisable variable quoting in a few places.#include \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::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::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::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::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(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":"\/**\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 \n#include \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(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(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(batch).data.data();\n length = dynamic_cast(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(batch);\n for(std::vector::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(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::iterator ptr = fields.begin(); ptr != fields.end(); ++ptr) {\n (*ptr)->printRow(rowId);\n std::cout << \"\\t\";\n }\n std::cout << \"\\n\";\n }\n }\n}\nFixed #52.\/**\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 \n#include \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(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(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(batch).data.data();\n length = dynamic_cast(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(batch);\n for(std::vector::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(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::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":"#include \n#include \n#include \n#include \/\/ 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(ndx);\n}\n\nbool AdaptiveStringColumn::Set(size_t ndx, const char* value) {\n\tassert(ndx < Size());\n\treturn TreeSet(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(ndx, value);\n}\n\nvoid AdaptiveStringColumn::Delete(size_t ndx) {\n\tassert(ndx < Size());\n\tTreeDelete(ndx);\n}\n\nsize_t AdaptiveStringColumn::Find(const char* value, size_t, size_t) const {\n\tassert(value);\n\treturn TreeFind(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(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 \/\/ 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\nFixed bug in AdaptiveStringColumn::Find#include \n#include \n#include \n#include \/\/ 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(ndx);\n}\n\nbool AdaptiveStringColumn::Set(size_t ndx, const char* value) {\n\tassert(ndx < Size());\n\treturn TreeSet(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(ndx, value);\n}\n\nvoid AdaptiveStringColumn::Delete(size_t ndx) {\n\tassert(ndx < Size());\n\tTreeDelete(ndx);\n}\n\nsize_t AdaptiveStringColumn::Find(const char* value, size_t start, size_t end) const {\n\tassert(value);\n\treturn TreeFind(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(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 \/\/ 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":"\/\/ 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 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 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 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[oneDNN ep] SLN performance improvement for bias (#13620)\/\/ 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 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 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 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 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":"\/*\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 \n#include \n#include \n\n#include \"Client.h\"\n#include \"Data.h\"\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \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 (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\nUpdate d_arnoldConnect.cpp\/*\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 \n#include \n#include \n\n#include \"Client.h\"\n#include \"Data.h\"\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \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 (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":"\/*\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 * .\n *\/\n\/\/ Class header file...\n#include \"XalanOutputStream.hpp\"\n\n\n\n#include \n#include \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(&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(&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(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}\nFixed bug in call to write() with XALAN_OLD_STYLE_CASTS.\/*\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 * .\n *\/\n\/\/ Class header file...\n#include \"XalanOutputStream.hpp\"\n\n\n\n#include \n#include \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(&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(&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(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":"\/\/\n\/\/ Copyright RIME Developers\n\/\/ Distributed under the BSD License\n\/\/\n\/\/ 2011-10-02 GONG Chen \n\/\/\n\n#include \n\n#ifdef RIME_ENABLE_LOGGING\n#include \n#endif \/\/ RIME_ENABLE_LOGGING\n\n#include \n#include \n#include \n#include \n#include \n#include \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\nfix(setup): avoid glog log macros conflict with macros of Windows\/\/\n\/\/ Copyright RIME Developers\n\/\/ Distributed under the BSD License\n\/\/\n\/\/ 2011-10-02 GONG Chen \n\/\/\n\n#include \n\n#ifdef RIME_ENABLE_LOGGING\n#ifdef _WIN32\n#define GLOG_NO_ABBREVIATED_SEVERITIES\n#endif \/\/ _WIN32\n#include \n#endif \/\/ RIME_ENABLE_LOGGING\n\n#include \n#include \n#include \n#include \n#include \n#include \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":"#include \n#include \n#include \n\n#include \"dasynq.h\"\n\nusing namespace dasynq;\n\nusing Loop_t = EventLoop;\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}\nUpdate example to match recent API changes.#include \n#include \n#include \n\n#include \"dasynq.h\"\n\nusing namespace dasynq;\n\nusing Loop_t = event_loop;\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":"#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std::literals;\n\nvoid requireZero( std::string_view view )\n{\n\tREQUIRE( view.data()[view.size()] == '\\0' );\n}\n\ntemplate\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() );\n\tstatic_assert( has_standard_container_typedefs() );\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 );\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 );\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 );\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 );\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[tests] Unit test the examples#include \n#include \n#include \n#include \n\n#include \n\nusing namespace std::literals;\n\nvoid requireZero( std::string_view view )\n{\n\tREQUIRE( view.data()[view.size()] == '\\0' );\n}\n\ntemplate\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() );\n\tstatic_assert( has_standard_container_typedefs() );\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 );\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 );\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 );\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 );\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":"#include \"EntriesModel.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \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(index.internalPointer());\n switch (role) {\n case Roles::CONTENT:\n data.setValue(entry->content());\n break;\n case Roles::DATETIME:\n data.setValue(entry->dateTime());\n break;\n case Qt::DisplayRole:\n case Roles::TITLE:\n data.setValue(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 EntriesModel::roleNames() const\n{\n QHash 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)\n{\n m_feed = feed;\n emit dataChanged(index(0, 0, QModelIndex{}),\n index(feed->size() - 1, 0, QModelIndex{}),\n QVector{Qt::DisplayRole, Roles::CONTENT, Roles::DATETIME, Roles::TITLE});\n}\n\nstd::shared_ptr EntriesModel::getEntry(const QModelIndex &idx) const\n{\n if (idx.isValid()) {\n return static_cast(idx.internalPointer())->shared_from_this();\n }\n return std::shared_ptr{};\n}\n\n} \/\/ feedling\nFix ``nullptr`` dereferencation if no feed was set on ``EntriesModel``#include \"EntriesModel.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \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(index.internalPointer());\n switch (role) {\n case Roles::CONTENT:\n data.setValue(entry->content());\n break;\n case Roles::DATETIME:\n data.setValue(entry->dateTime());\n break;\n case Qt::DisplayRole:\n case Roles::TITLE:\n data.setValue(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 EntriesModel::roleNames() const\n{\n QHash 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)\n{\n m_feed = feed;\n emit dataChanged(index(0, 0, QModelIndex{}),\n index(feed->size() - 1, 0, QModelIndex{}),\n QVector{Qt::DisplayRole, Roles::CONTENT, Roles::DATETIME, Roles::TITLE});\n}\n\nstd::shared_ptr EntriesModel::getEntry(const QModelIndex &idx) const\n{\n if (idx.isValid()) {\n return static_cast(idx.internalPointer())->shared_from_this();\n }\n return std::shared_ptr{};\n}\n\n} \/\/ feedling\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \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::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(CModInfo &info)\n{\n\tinfo.SetWikiPage(\"Twitch\");\n\tinfo.SetHasArgs(true);\n}\n\nNETWORKMODULEDEFS(TwitchTMI, \"Twitch IRC helper module\")\nAdd USERNOTICE handler#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \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::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, \"<<>> \" + 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(CModInfo &info)\n{\n\tinfo.SetWikiPage(\"Twitch\");\n\tinfo.SetHasArgs(true);\n}\n\nNETWORKMODULEDEFS(TwitchTMI, \"Twitch IRC helper module\")\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \n#include \n#include \n#include \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(); }\nUpdate with current size\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \n#include \n#include \n#include \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":"\/*\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 \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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\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(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(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(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(&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(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\nEnable memory idler for aarch64\/*\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 \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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\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(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(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(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(&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(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":"\/*\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 \n\n#ifdef _WIN32\n#include \n#include \n#include \n#include \n#include \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\nDon't call strlen(nullptr) in mkdtemp and mkstemp\/*\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 \n\n#ifdef _WIN32\n#include \n#include \n\n#include \n#include \n#include \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":"#include \"rs-config.h\"\n\n#include \"..\/third-party\/json.hpp\"\n\n#include \"model-views.h\"\n\n#include \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(t)),\n std::istreambuf_iterator());\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}Visual Studio 2019 compilation fix#include \"rs-config.h\"\n\n#include \"..\/third-party\/json.hpp\"\n\n#include \"model-views.h\"\n\n#include \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(t)),\n std::istreambuf_iterator());\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();\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":"#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\nFix on the cycle counter#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":"\/*\n * Copyright (C) 2014 Pavel Kirienko \n *\/\n\n#ifndef UAVCAN_NODE_SERVICE_CLIENT_HPP_INCLUDED\n#define UAVCAN_NODE_SERVICE_CLIENT_HPP_INCLUDED\n\n#include \n#include \n#include \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 \n#endif\n\nnamespace uavcan\n{\n\ntemplate \nclass UAVCAN_EXPORT ServiceResponseTransferListenerInstantiationHelper\n{\npublic: \/\/ so much templating it hurts\n typedef typename TransferListenerInstantiationHelper::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 \nstruct UAVCAN_EXPORT ServiceCallResult\n{\n typedef ReceivedDataStructure 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 \nstatic Stream& operator<<(Stream& s, const ServiceCallResult& 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 = UAVCAN_CPP11\n typename Callback_ = std::function&)>\n#else\n typename Callback_ = void (*)(const ServiceCallResult&)\n#endif\n >\nclass UAVCAN_EXPORT ServiceClient\n : public GenericSubscriber::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 ServiceCallResultType;\n typedef Callback_ Callback;\n\nprivate:\n typedef ServiceClient SelfType;\n typedef GenericPublisher PublisherType;\n typedef typename ServiceResponseTransferListenerInstantiationHelper::Type TransferListenerType;\n typedef GenericSubscriber SubscriberType;\n\n PublisherType publisher_;\n Callback callback_;\n\n bool isCallbackValid() const { return try_implicit_cast(callback_, true); }\n\n void invokeCallback(ServiceCallResultType& result);\n\n virtual void handleReceivedDataStruct(ReceivedDataStructure& 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 \nvoid ServiceClient::invokeCallback(ServiceCallResultType& result)\n{\n if (isCallbackValid())\n {\n callback_(result);\n }\n else\n {\n handleFatalError(\"Srv client clbk\");\n }\n}\n\ntemplate \nvoid ServiceClient::handleReceivedDataStruct(ReceivedDataStructure& 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 \nvoid ServiceClient::handleDeadline(MonotonicTime)\n{\n const TransferListenerType* const listener = SubscriberType::getTransferListener();\n if (listener)\n {\n const typename TransferListenerType::ExpectedResponseParams erp = listener->getExpectedResponseParams();\n ReceivedDataStructure& 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 \nint ServiceClient::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 \nvoid ServiceClient::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\nFixed error handling in ServiceClient\/*\n * Copyright (C) 2014 Pavel Kirienko \n *\/\n\n#ifndef UAVCAN_NODE_SERVICE_CLIENT_HPP_INCLUDED\n#define UAVCAN_NODE_SERVICE_CLIENT_HPP_INCLUDED\n\n#include \n#include \n#include \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 \n#endif\n\nnamespace uavcan\n{\n\ntemplate \nclass UAVCAN_EXPORT ServiceResponseTransferListenerInstantiationHelper\n{\npublic: \/\/ so much templating it hurts\n typedef typename TransferListenerInstantiationHelper::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 \nstruct UAVCAN_EXPORT ServiceCallResult\n{\n typedef ReceivedDataStructure 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 \nstatic Stream& operator<<(Stream& s, const ServiceCallResult& 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 = UAVCAN_CPP11\n typename Callback_ = std::function&)>\n#else\n typename Callback_ = void (*)(const ServiceCallResult&)\n#endif\n >\nclass UAVCAN_EXPORT ServiceClient\n : public GenericSubscriber::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 ServiceCallResultType;\n typedef Callback_ Callback;\n\nprivate:\n typedef ServiceClient SelfType;\n typedef GenericPublisher PublisherType;\n typedef typename ServiceResponseTransferListenerInstantiationHelper::Type TransferListenerType;\n typedef GenericSubscriber SubscriberType;\n\n PublisherType publisher_;\n Callback callback_;\n\n bool isCallbackValid() const { return try_implicit_cast(callback_, true); }\n\n void invokeCallback(ServiceCallResultType& result);\n\n virtual void handleReceivedDataStruct(ReceivedDataStructure& 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 \nvoid ServiceClient::invokeCallback(ServiceCallResultType& result)\n{\n if (isCallbackValid())\n {\n callback_(result);\n }\n else\n {\n handleFatalError(\"Srv client clbk\");\n }\n}\n\ntemplate \nvoid ServiceClient::handleReceivedDataStruct(ReceivedDataStructure& 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 \nvoid ServiceClient::handleDeadline(MonotonicTime)\n{\n const TransferListenerType* const listener = SubscriberType::getTransferListener();\n if (listener)\n {\n const typename TransferListenerType::ExpectedResponseParams erp = listener->getExpectedResponseParams();\n ReceivedDataStructure& 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 \nint ServiceClient::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 \nvoid ServiceClient::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":"Connections virkar<|endoftext|>"} {"text":"#include \n#include \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(&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(handle);\n auto arrayType = static_cast(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(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 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(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}Fixed typo.#include \n#include \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(&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(handle);\n auto arrayType = static_cast(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(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 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(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":"#include \n#include \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}asserting#include \n#include \n#include \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":"#include \n#include \n#include \n#include \n#include \n#include \n#include \"IO.hpp\"\n#include \"common.h\"\n#include \"mkl.h\"\n#include \"BenchmarkUtils.hpp\"\n#include \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> 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 values;\n std::vector col_ind;\n std::vector 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 apply(std::vector x) = 0;\n};\n\n\/\/ Equivalent to un-precontitioned CG\nclass IdentityPreconditioner : public Preconditioner {\n public:\n virtual std::vector apply(std::vector 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 apply(std::vector 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 \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 r(n); \/\/ residual\n std::vector b(rhs, rhs + n); \/\/ rhs\n std::vector p(n); \/\/\n std::vector 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 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 rhs = sparsebench::io::readVector(std::string(argv[4]));\n\n std::vector 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(n, nnzs, col_ind, row_ptr, values, &rhs[0], &sol[0], iterations, verbose);\n t.toc(\"cg:all\");\n\n std::vector 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}\nFix ILU pc#include \n#include \n#include \n#include \n#include \n#include \n#include \"IO.hpp\"\n#include \"common.h\"\n#include \"mkl.h\"\n#include \"BenchmarkUtils.hpp\"\n#include \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> 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 values;\n std::vector col_ind;\n std::vector 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 apply(std::vector x) = 0;\n};\n\n\/\/ Equivalent to un-precontitioned CG\nclass IdentityPreconditioner : public Preconditioner {\n public:\n virtual std::vector apply(std::vector 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 apply(std::vector 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 \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 r(n); \/\/ residual\n std::vector b(rhs, rhs + n); \/\/ rhs\n std::vector p(n); \/\/\n std::vector 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 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 rhs = sparsebench::io::readVector(std::string(argv[4]));\n\n std::vector 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(n, nnzs, col_ind, row_ptr, values, &rhs[0], &sol[0], iterations, verbose);\n t.toc(\"cg:all\");\n\n std::vector 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":"\/*\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(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(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(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(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(styleRule->getStyle().self());\n selector->registerToRuleList(this, declaration, mediaList);\n }\n }\n } else if (CSSMediaRuleImp* mediaRule = dynamic_cast(rule.self())) {\n auto ruleList = dynamic_cast(mediaRule->getCssRules().self());\n if (ruleList) {\n MediaListImp* mediaList = dynamic_cast(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(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& 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 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 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((*i)->getStyleSheet().self())) {\n if (CSSRuleListImp* ruleList = dynamic_cast(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(CSSRuleListImp::collectRules) : Fix a bug; cf. html4\/at-import-004.htm\/*\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(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(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(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(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(styleRule->getStyle().self());\n selector->registerToRuleList(this, declaration, mediaList);\n }\n }\n } else if (CSSMediaRuleImp* mediaRule = dynamic_cast(rule.self())) {\n auto ruleList = dynamic_cast(mediaRule->getCssRules().self());\n if (ruleList) {\n MediaListImp* mediaList = dynamic_cast(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(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& 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 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 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((*i)->getMedia().self()))\n mediaList = media;\n \/\/ TODO: else ...\n if (CSSStyleSheetImp* sheet = dynamic_cast((*i)->getStyleSheet().self())) {\n if (CSSRuleListImp* ruleList = dynamic_cast(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":"#ifndef QUORIDOR_BOARD_HPP_\n#define QUORIDOR_BOARD_HPP_\n\n#include \n\n#include \n#include \n#include \n#include \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);\n void add_occupied(const pos_t &pos, std::shared_ptr pawn);\n void rm_occupied(const pos_t &pos);\n pos_t pawn_pos(std::shared_ptr pawn) const;\n\n int make_move(BoardMoves move, std::shared_ptr pawn);\n bool is_at_opposite_side(std::shared_ptr pawn) const;\n int add_wall(const Wall &wall);\n\nprivate:\n BoardMoves recalc_move(BoardMoves move, std::shared_ptr pawn);\n int make_walking_move(BoardMoves move, std::shared_ptr 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> occ_fields_;\n std::map, pos_t> pawn_pos_;\n mutable std::vector> sides_;\n std::map, int> pawn_sides_;\n std::map> walls_;\n};\n\n} \/* namespace Quoridor *\/\n\n#endif \/* QUORIDOR_BOARD_HPP_ *\/\nImplement few operators in struct pos_t.#ifndef QUORIDOR_BOARD_HPP_\n#define QUORIDOR_BOARD_HPP_\n\n#include \n\n#include \n#include \n#include \n#include \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);\n void add_occupied(const pos_t &pos, std::shared_ptr pawn);\n void rm_occupied(const pos_t &pos);\n pos_t pawn_pos(std::shared_ptr pawn) const;\n\n int make_move(BoardMoves move, std::shared_ptr pawn);\n bool is_at_opposite_side(std::shared_ptr pawn) const;\n int add_wall(const Wall &wall);\n\nprivate:\n BoardMoves recalc_move(BoardMoves move, std::shared_ptr pawn);\n int make_walking_move(BoardMoves move, std::shared_ptr 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> occ_fields_;\n std::map, pos_t> pawn_pos_;\n mutable std::vector> sides_;\n std::map, int> pawn_sides_;\n std::map> walls_;\n};\n\n} \/* namespace Quoridor *\/\n\n#endif \/* QUORIDOR_BOARD_HPP_ *\/\n<|endoftext|>"} {"text":"\/*\n * File: KrakenBattle.cpp\n * Author: Kjell Hedstrom\n *\n * Created on November 24, 2015\n *\/\n\n#include \"KrakenBattle.h\"\n#include \n#include \n#include \n\nnamespace {\n const std::string emptyUUID = {\"00000000-0000-0000-0000-000000000000\"};\n const std::vector 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 uuidoptional: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 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 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(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 = \"\";\n switch (type) {\n case SendType::Data : textType = \"\"; break;\n case SendType::Done : textType = \"\"; break;\n case SendType::Error : textType = \"\"; break;\n case SendType::End : textType = \"\"; break;\n default:\n LOG(FATAL) << \"Unknown Send::Type: \" << static_cast(type);\n }\n return textType;\n }\n\n std::string EnumToString(const KrakenBattle::ProgressType& type) {\n std::string textType = \"\";\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(type);\n }\n return textType;\n }\n} \/\/ namespace KrakenBattle\nFixed comment\/*\n * File: KrakenBattle.cpp\n * Author: Kjell Hedstrom\n *\n * Created on November 24, 2015\n *\/\n\n#include \"KrakenBattle.h\"\n#include \n#include \n#include \n\nnamespace {\n const std::string emptyUUID = {\"00000000-0000-0000-0000-000000000000\"};\n const std::vector 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 uuidoptional: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 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 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(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 = \"\";\n switch (type) {\n case SendType::Data : textType = \"\"; break;\n case SendType::Done : textType = \"\"; break;\n case SendType::Error : textType = \"\"; break;\n case SendType::End : textType = \"\"; break;\n default:\n LOG(FATAL) << \"Unknown Send::Type: \" << static_cast(type);\n }\n return textType;\n }\n\n std::string EnumToString(const KrakenBattle::ProgressType& type) {\n std::string textType = \"\";\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(type);\n }\n return textType;\n }\n} \/\/ namespace KrakenBattle\n<|endoftext|>"} {"text":"\/*\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\/\/ Jlj\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\/\/ vflj\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(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; iGetImageCount(); 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\nIDの64bit対応\/*\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\/\/ Jlj\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\/\/ vflj\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(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; iGetImageCount(); 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":"\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\nBodyCentredBodyDirectionDynamicFrame::\nBodyCentredBodyDirectionDynamicFrame(\n not_null const*> const ephemeris,\n not_null const primary,\n not_null 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\nRigidMotion\nBodyCentredBodyDirectionDynamicFrame::\n ToThisFrameAtTime(Instant const& t) const {\n DegreesOfFreedom const primary_degrees_of_freedom =\n primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);\n DegreesOfFreedom const secondary_degrees_of_freedom =\n secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);\n\n Rotation rotation =\n Rotation::Identity();\n AngularVelocity angular_velocity;\n ComputeAngularDegreesOfFreedom(primary_degrees_of_freedom,\n secondary_degrees_of_freedom,\n &rotation,\n &angular_velocity);\n\n RigidTransformation const\n rigid_transformation(primary_degrees_of_freedom.position(),\n ThisFrame::origin,\n rotation.Forget());\n return RigidMotion(\n rigid_transformation,\n angular_velocity,\n primary_degrees_of_freedom.velocity());\n}\n\ntemplate\nvoid BodyCentredBodyDirectionDynamicFrame::\nWriteToMessage(not_null 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\nnot_null>>\nBodyCentredBodyDirectionDynamicFrame::ReadFromMessage(\n not_null const*> const ephemeris,\n serialization::BodyCentredBodyDirectionDynamicFrame const & message) {\n return std::make_unique(\n ephemeris,\n ephemeris->body_for_serialization_index(message.primary()),\n ephemeris->body_for_serialization_index(message.secondary()));\n}\n\ntemplate\nVector\nBodyCentredBodyDirectionDynamicFrame::\nGravitationalAcceleration(Instant const& t,\n Position const& q) const {\n return ephemeris_->ComputeGravitationalAccelerationOnMasslessBody(q, t);\n}\n\ntemplate\nAcceleratedRigidMotion\nBodyCentredBodyDirectionDynamicFrame::\nMotionOfThisFrame(Instant const& t) const {\n DegreesOfFreedom const primary_degrees_of_freedom =\n primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);\n DegreesOfFreedom const secondary_degrees_of_freedom =\n secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);\n\n Vector const primary_acceleration =\n ephemeris_->ComputeGravitationalAccelerationOnMassiveBody(primary_, t);\n Vector 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 const primary_secondary =\n primary_degrees_of_freedom - secondary_degrees_of_freedom;\n Displacement const& r = primary_secondary.displacement();\n Velocity const& ṙ = primary_secondary.velocity();\n Vector const r̈ =\n primary_acceleration - secondary_acceleration;\n AngularVelocity const& ω =\n to_this_frame.angular_velocity_of_to_frame();\n Variation> const\n angular_acceleration_of_to_frame =\n (Wedge(r, r̈) * Radian - 2 * ω * InnerProduct(r, ṙ)) \/\n InnerProduct(r, r);\n\n Vector const& acceleration_of_to_frame_origin =\n primary_acceleration;\n return AcceleratedRigidMotion(\n to_this_frame,\n angular_acceleration_of_to_frame,\n acceleration_of_to_frame_origin);\n}\n\ntemplate\nvoid BodyCentredBodyDirectionDynamicFrame::\nComputeAngularDegreesOfFreedom(\n DegreesOfFreedom const& primary_degrees_of_freedom,\n DegreesOfFreedom const& secondary_degrees_of_freedom,\n not_null*> const rotation,\n not_null*> const angular_velocity) {\n RelativeDegreesOfFreedom const reference =\n secondary_degrees_of_freedom - primary_degrees_of_freedom;\n Displacement const& reference_direction =\n reference.displacement();\n Velocity reference_normal = reference.velocity();\n reference_direction.template Orthogonalize(&reference_normal);\n Bivector, InertialFrame> const reference_binormal =\n Wedge(reference_direction, reference_normal);\n *rotation = Rotation(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\nCleanup.\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\nBodyCentredBodyDirectionDynamicFrame::\nBodyCentredBodyDirectionDynamicFrame(\n not_null const*> const ephemeris,\n not_null const primary,\n not_null 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\nRigidMotion\nBodyCentredBodyDirectionDynamicFrame::\n ToThisFrameAtTime(Instant const& t) const {\n DegreesOfFreedom const primary_degrees_of_freedom =\n primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);\n DegreesOfFreedom const secondary_degrees_of_freedom =\n secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);\n\n Rotation rotation =\n Rotation::Identity();\n AngularVelocity angular_velocity;\n ComputeAngularDegreesOfFreedom(primary_degrees_of_freedom,\n secondary_degrees_of_freedom,\n &rotation,\n &angular_velocity);\n\n RigidTransformation const\n rigid_transformation(primary_degrees_of_freedom.position(),\n ThisFrame::origin,\n rotation.Forget());\n return RigidMotion(\n rigid_transformation,\n angular_velocity,\n primary_degrees_of_freedom.velocity());\n}\n\ntemplate\nvoid BodyCentredBodyDirectionDynamicFrame::\nWriteToMessage(not_null 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\nnot_null>>\nBodyCentredBodyDirectionDynamicFrame::ReadFromMessage(\n not_null const*> const ephemeris,\n serialization::BodyCentredBodyDirectionDynamicFrame const & message) {\n return std::make_unique(\n ephemeris,\n ephemeris->body_for_serialization_index(message.primary()),\n ephemeris->body_for_serialization_index(message.secondary()));\n}\n\ntemplate\nVector\nBodyCentredBodyDirectionDynamicFrame::\nGravitationalAcceleration(Instant const& t,\n Position const& q) const {\n return ephemeris_->ComputeGravitationalAccelerationOnMasslessBody(q, t);\n}\n\ntemplate\nAcceleratedRigidMotion\nBodyCentredBodyDirectionDynamicFrame::\nMotionOfThisFrame(Instant const& t) const {\n DegreesOfFreedom const primary_degrees_of_freedom =\n primary_trajectory_->EvaluateDegreesOfFreedom(t, &primary_hint_);\n DegreesOfFreedom const secondary_degrees_of_freedom =\n secondary_trajectory_->EvaluateDegreesOfFreedom(t, &secondary_hint_);\n\n Vector const primary_acceleration =\n ephemeris_->ComputeGravitationalAccelerationOnMassiveBody(primary_, t);\n Vector 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 const secondary_primary =\n secondary_degrees_of_freedom - primary_degrees_of_freedom;\n Displacement const& r = secondary_primary.displacement();\n Velocity const& ṙ = secondary_primary.velocity();\n Vector const r̈ =\n secondary_acceleration - primary_acceleration;\n AngularVelocity const& ω =\n to_this_frame.angular_velocity_of_to_frame();\n Variation> const\n angular_acceleration_of_to_frame =\n (Wedge(r, r̈) * Radian - 2 * ω * InnerProduct(r, ṙ)) \/\n InnerProduct(r, r);\n\n Vector const& acceleration_of_to_frame_origin =\n primary_acceleration;\n return AcceleratedRigidMotion(\n to_this_frame,\n angular_acceleration_of_to_frame,\n acceleration_of_to_frame_origin);\n}\n\ntemplate\nvoid BodyCentredBodyDirectionDynamicFrame::\nComputeAngularDegreesOfFreedom(\n DegreesOfFreedom const& primary_degrees_of_freedom,\n DegreesOfFreedom const& secondary_degrees_of_freedom,\n not_null*> const rotation,\n not_null*> const angular_velocity) {\n RelativeDegreesOfFreedom const reference =\n secondary_degrees_of_freedom - primary_degrees_of_freedom;\n Displacement const& reference_direction =\n reference.displacement();\n Velocity reference_normal = reference.velocity();\n reference_direction.template Orthogonalize(&reference_normal);\n Bivector, InertialFrame> const reference_binormal =\n Wedge(reference_direction, reference_normal);\n *rotation = Rotation(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":"#include \n#include \n#include \n#include \n\/\/-----------------------------------------------------------------------------\n#include \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\/\/-----------------------------------------------------------------------------\nAsí también se despacha en seguida#include \n#include \n#include \n#include \n\/\/-----------------------------------------------------------------------------\n#include \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":"\/*\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 cacheArray;\n\n foreach (QSpiAdaptor* obj, spiBridge->cacheObjects()) {\n cacheArray << obj->getCacheItem();\n }\n return cacheArray;\n}\nRemove unneded temporary var.\/*\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 cacheArray;\n\n foreach (QSpiAdaptor* obj, spiBridge->cacheObjects()) {\n cacheArray << obj->getCacheItem();\n }\n return cacheArray;\n}\n<|endoftext|>"} {"text":"#ifndef RETRIEVER_CACHE_HPP\n#define RETRIEVER_CACHE_HPP\n\n#include \"list.hpp\"\n#include \n#include \n#include \n\ntemplate class CacheItem : public Item {\npublic:\n CacheItem(K k, V v) : key(k), value(v){};\n K key;\n V value;\n};\n\ntemplate class Cache {\npublic:\n explicit Cache(const int capacity) : capacity(capacity) {\n lookUpTable = std::unordered_map *>(capacity);\n };\n\n void set(const K key, const V value) {\n std::unique_lock lock(tableSMutex);\n\n auto mapIt = lookUpTable.find(key);\n if (mapIt == lookUpTable.end()) {\n std::unique_ptr> item(new CacheItem(key, value));\n if (lookUpTable.size() == capacity) {\n auto toRemove = kList.back;\n kList.remove(toRemove);\n lookUpTable.erase(\n lookUpTable.find(dynamic_cast *>(toRemove)->key));\n }\n kList.pushFront(dynamic_cast(item.get()));\n } else {\n auto item = mapIt->second;\n item->value = value;\n kList.moveToFront(dynamic_cast(item.get()));\n }\n };\n\n V get(const K key) {\n std::shared_lock lock(tableSMutex);\n\n auto mapIt = lookUpTable.find(key);\n if (mapIt == lookUpTable.end()) {\n return V();\n }\n kList.moveToFront(dynamic_cast(mapIt->second->get()));\n return mapIt->second->value;\n };\n\nprivate:\n Cache(){};\n\n int capacity;\n std::unordered_map>> lookUpTable;\n std::shared_mutex tableSMutex;\n List kList;\n};\n\n#endif\nfix: initialize lookuptable with correct type#ifndef RETRIEVER_CACHE_HPP\n#define RETRIEVER_CACHE_HPP\n\n#include \"list.hpp\"\n#include \n#include \n#include \n\ntemplate class CacheItem : public Item {\npublic:\n CacheItem(K k, V v) : key(k), value(v){};\n K key;\n V value;\n};\n\ntemplate class Cache {\npublic:\n explicit Cache(const int capacity) : capacity(capacity) {\n lookUpTable =\n std::unordered_map>>(capacity);\n };\n\n void set(const K key, const V value) {\n std::unique_lock lock(tableSMutex);\n\n auto mapIt = lookUpTable.find(key);\n if (mapIt == lookUpTable.end()) {\n std::unique_ptr> item(new CacheItem(key, value));\n if (lookUpTable.size() == capacity) {\n auto toRemove = kList.back;\n kList.remove(toRemove);\n lookUpTable.erase(\n lookUpTable.find(dynamic_cast *>(toRemove)->key));\n }\n kList.pushFront(dynamic_cast(item.get()));\n } else {\n auto item = mapIt->second;\n item->value = value;\n kList.moveToFront(dynamic_cast(item.get()));\n }\n };\n\n V get(const K key) {\n std::shared_lock lock(tableSMutex);\n\n auto mapIt = lookUpTable.find(key);\n if (mapIt == lookUpTable.end()) {\n return V();\n }\n kList.moveToFront(dynamic_cast(mapIt->second->get()));\n return mapIt->second->value;\n };\n\nprivate:\n Cache(){};\n\n int capacity;\n std::unordered_map>> lookUpTable;\n std::shared_mutex tableSMutex;\n List kList;\n};\n\n#endif\n<|endoftext|>"} {"text":"#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 \n#include \n\n#include \n\nnamespace Kakoune\n{\n\nClient::Client(std::unique_ptr&& ui,\n std::unique_ptr&& 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());\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::Keys);\n \/\/ steal keys as we might receive new keys while handling them.\n Vector 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();\n HashMap 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());\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();\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, : reload | n, : 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());\n m_ui_pending |= Draw;\n }\n}\n\nvoid Client::menu_show(Vector 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}\nObtain a new window for a client before releasing the current one#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 \n#include \n\n#include \n\nnamespace Kakoune\n{\n\nClient::Client(std::unique_ptr&& ui,\n std::unique_ptr&& 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());\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::Keys);\n \/\/ steal keys as we might receive new keys while handling them.\n Vector 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();\n HashMap 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());\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();\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, : reload | n, : 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());\n m_ui_pending |= Draw;\n }\n}\n\nvoid Client::menu_show(Vector 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":"fix bug in setting min file size for logger<|endoftext|>"} {"text":"\/* 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 \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}\nDo not set a default material for objects in view. Handle scene viewing in initialization.\/* 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 \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":"#pragma once\n\n#include \n#include \n#include \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()\nAdding check not null#pragma once\n\n#include \n#include \n#include \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\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":"\/********************************************************************\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 \n#include \t\t\/\/ strncpy()\n#include \t\t\/\/ struct stat\n#include \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\nmake sure that M1xx programs are still found even when [DISPLAY]PROGRAM_PREFIX does not end with a slash\/********************************************************************\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 \n#include \t\t\/\/ strncpy()\n#include \t\t\/\/ struct stat\n#include \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":"\/* OpenHoW\n * Copyright (C) 2017-2020 Mark Sowden \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 .\n *\/\n\n#include \n#include \n#include \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\nstub out redraw for frontend until this is rewritten\/* OpenHoW\n * Copyright (C) 2017-2020 Mark Sowden \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 .\n *\/\n\n#include \n#include \n#include \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":"\/************************************************************************\/\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 \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}\nresize example: whitespace cleanups\/************************************************************************\/\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 \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":"\/\/ 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\nImprove the shadow drawing parameters (#3499)\/\/ 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":"\/*\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 \n#include \n#include \n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \n#include \n#include \n#include \n#include \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\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::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().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 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::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::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 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 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 create_smart_ban_plugin(torrent* t, void*)\n\t{\n\t\treturn boost::shared_ptr(new smart_ban_plugin(*t));\n\t}\n\n}\n\n\nfix smart ban assert when closing a torrent with a failing piece\/*\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 \n#include \n#include \n\n#ifdef _MSC_VER\n#pragma warning(pop)\n#endif\n\n#include \n#include \n#include \n#include \n#include \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\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::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().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 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::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::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 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 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 create_smart_ban_plugin(torrent* t, void*)\n\t{\n\t\treturn boost::shared_ptr(new smart_ban_plugin(*t));\n\t}\n\n}\n\n\n<|endoftext|>"} {"text":"\/**\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 \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(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 (fReader));\n \/\/ read the header from the previous analysis stage\n \/\/\n fHeader = dynamic_cast(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}\nAdd some small fixes e.g. initialize all members of the JPetTaskIO\/**\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 \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(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 (fReader));\n \/\/ read the header from the previous analysis stage\n \/\/\n fHeader = dynamic_cast(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":" \/*************************************************************************\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 \n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_GENERAL_H_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_H_\n#include \n#endif\n\n\/\/________________________________\n\/\/ interface includes\n\n\/\/________________________________\n\/\/ includes of other projects\n\n#ifndef _RTL_USTRBUF_HXX_\n#include \n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include \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

\n It's a list of named values, packed inside this any.\n Following protocol is used:\n

\n

    \n
  • \n \"SaveArguments\" [sequence< css.beans.NamedValue >]\n
    \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
  • \n \"SendDispatchResult\" [css.frame.DispatchResultEvent]\n
    \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
  • \n \"Deactivate\" [boolean]\n
    \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>= 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\nINTEGRATION: 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 \/*************************************************************************\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 \n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_\n#include \n#endif\n\n#ifndef __FRAMEWORK_GENERAL_H_\n#include \n#endif\n\n#ifndef __FRAMEWORK_SERVICES_H_\n#include \n#endif\n\n\/\/________________________________\n\/\/ interface includes\n\n\/\/________________________________\n\/\/ includes of other projects\n\n#ifndef _RTL_USTRBUF_HXX_\n#include \n#endif\n\n#ifndef _SV_SVAPP_HXX\n#include \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

    \n It's a list of named values, packed inside this any.\n Following protocol is used:\n

    \n

      \n
    • \n \"SaveArguments\" [sequence< css.beans.NamedValue >]\n
      \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
    • \n \"SendDispatchResult\" [css.frame.DispatchResultEvent]\n
      \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
    • \n \"Deactivate\" [boolean]\n
      \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>= 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":"#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}\nFix compilation error in HDD's unittest#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":"\/\/ 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 wire_list;\r\n\r\n\t\tstd::list sketches_to_delete;\r\n\r\n\t\tfor(std::list::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 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 list, double height_or_angle, bool solid_if_possible, bool revolution_not_extrusion, bool add_new_objects)\r\n{\r\n\tstd::list faces_or_wires;\r\n\r\n\tstd::list sketches_or_faces_to_delete;\r\n\r\n\tfor(std::list::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 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::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 faces;\n\tstd::list pipe_shapes;\n\tif(ConvertSketchToFaceOrWire(profile, faces, true))\n\t{\n\t\tfor(std::list::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::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 list, bool make_solid)\r\n{\r\n\tstd::list wire_list;\r\n\tfor(std::list::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 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 *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 *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 &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::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 &faces_or_wires, std::list& new_shapes, const gp_Vec& extrude_vector)\r\n{\r\n\ttry{\r\n\t\tfor(std::list::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 &faces_or_wires, std::list& new_shapes, const gp_Ax1& axis, double angle)\r\n{\r\n\ttry{\r\n\t\tfor(std::list::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\nChanged default axis of revolution to vector along X axis, because I'm lazy :)\/\/ 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 wire_list;\r\n\r\n\t\tstd::list sketches_to_delete;\r\n\r\n\t\tfor(std::list::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 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 list, double height_or_angle, bool solid_if_possible, bool revolution_not_extrusion, bool add_new_objects)\r\n{\r\n\tstd::list faces_or_wires;\r\n\r\n\tstd::list sketches_or_faces_to_delete;\r\n\r\n\tfor(std::list::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 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::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 faces;\r\n\tstd::list pipe_shapes;\r\n\tif(ConvertSketchToFaceOrWire(profile, faces, true))\r\n\t{\r\n\t\tfor(std::list::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::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 list, bool make_solid)\r\n{\r\n\tstd::list wire_list;\r\n\tfor(std::list::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 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 *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 *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 &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::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 &faces_or_wires, std::list& new_shapes, const gp_Vec& extrude_vector)\r\n{\r\n\ttry{\r\n\t\tfor(std::list::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 &faces_or_wires, std::list& new_shapes, const gp_Ax1& axis, double angle)\r\n{\r\n\ttry{\r\n\t\tfor(std::list::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":"\/\/ Licence 2\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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; itype = 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}\nwrite\/\/ Licence 2\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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; itype = 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":"\/*********************************************************************************\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"inviwosplashscreen.h\"\n#include \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}\napps: fixed crash on exit due to processor widget ownership\/*********************************************************************************\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"inviwosplashscreen.h\"\n#include \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":"#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\"<hahahah#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\"<"} {"text":"\/\/ Copyright 2016 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF 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 \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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 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(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((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\nDuring the output check I need to break.\/\/ Copyright 2016 Alessio Sclocco \n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF 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 \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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 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(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((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":"\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 && iString());\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 && iString());\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\nFixed Windows file reading bug (I think).\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 && iString());\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 && iString());\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":"\/* 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 \n#include \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; ibitmap.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; ibitmap.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 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; i255) 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; ybitmap.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}\ncleaning dead code\/* 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 \n#include \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; ibitmap.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; ibitmap.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 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; i255) 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; ibitmap.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":"#include \"slist_eval.h\"\n#include \"slist_parser.h\"\n#include \"slist_log.h\"\n\n#include \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());\n name_node->type = node_type::name;\n name_node->value = proc->name;\n\n node_ptr root(std::make_shared());\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(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());\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());\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}Fixed environment merge for tail call optim.#include \"slist_eval.h\"\n#include \"slist_parser.h\"\n#include \"slist_log.h\"\n\n#include \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());\n name_node->type = node_type::name;\n name_node->value = proc->name;\n\n node_ptr root(std::make_shared());\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(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());\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());\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":"\/\/ 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 .\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 &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}\nCalc steps only if waypoint exists\/\/ 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 .\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 &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":"\/* 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 \n#include \n#include \n\n#ifdef __unix__\n#include \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());\n}\n\nvoid\ncontext::set_logger(std::unique_ptr 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 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 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 ctx, problem& pb)\n{\n check(pb);\n\n std::map params;\n\n return mitm_solve(ctx, pb, params);\n}\n\nresult\nsolve(std::shared_ptr ctx,\n problem& pb,\n const std::map& params)\n{\n check(pb);\n\n return mitm_solve(ctx, pb, params);\n}\n\nresult\noptimize(std::shared_ptr ctx,\n problem& pb,\n const std::map& params)\n{\n check(pb);\n\n return mitm_optimize(ctx, pb, params);\n}\n\nresult\noptimize(std::shared_ptr ctx, problem& pb)\n{\n check(pb);\n\n std::map params;\n\n return mitm_optimize(ctx, pb, params);\n}\n\ntemplate \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& 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& 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}\nlpcore: fix log priority for log, error, warning, info functions\/* 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 \n#include \n#include \n\n#ifdef __unix__\n#include \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());\n}\n\nvoid\ncontext::set_logger(std::unique_ptr 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 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 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 ctx, problem& pb)\n{\n check(pb);\n\n std::map params;\n\n return mitm_solve(ctx, pb, params);\n}\n\nresult\nsolve(std::shared_ptr ctx,\n problem& pb,\n const std::map& params)\n{\n check(pb);\n\n return mitm_solve(ctx, pb, params);\n}\n\nresult\noptimize(std::shared_ptr ctx,\n problem& pb,\n const std::map& params)\n{\n check(pb);\n\n return mitm_optimize(ctx, pb, params);\n}\n\nresult\noptimize(std::shared_ptr ctx, problem& pb)\n{\n check(pb);\n\n std::map params;\n\n return mitm_optimize(ctx, pb, params);\n}\n\ntemplate \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& 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& 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":"\/*\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 \n#include \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; \/\/ 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 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 :\ntidy up\/*\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 \n#include \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; \/\/ 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 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":"\/*\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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}\nfix return instead of goto cleanup bug in matcher\/*\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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":"#include \"commit.h\"\n\nPersistent Commit::constructor_template;\n\nvoid Commit::Init(Handle target) {\n\tHandleScope scope;\n\n\tLocal t = FunctionTemplate::New(New);\n\tconstructor_template = Persistent::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 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(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 parentObjectTemplate = ObjectTemplate::New();\n\tparentObjectTemplate->SetInternalFieldCount(1);\n\tparentObjectTemplate->SetIndexedPropertyHandler(IndexedParentGetter);\n\n\tHandle 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 Commit::GetTree(const Arguments& args) {\n\tHandleScope scope;\n\n\tCommit *commit = ObjectWrap::Unwrap(args.This());\n\n\tconst git_tree *tree = git_commit_tree(commit->commit_);\n\n\tTree *treeObject = commit->repository_->wrapTree(const_cast(tree));\n\treturn treeObject->handle_;\n}\n\nHandle Commit::GetParent(const Arguments& args) {\n\tHandleScope scope;\n\n\tCommit *commit = ObjectWrap::Unwrap(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}\ncleanup#include \"commit.h\"\n\nPersistent Commit::constructor_template;\n\nvoid Commit::Init(Handle target) {\n\tHandleScope scope;\n\n\tLocal t = FunctionTemplate::New(New);\n\tconstructor_template = Persistent::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 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(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 Commit::GetTree(const Arguments& args) {\n\tHandleScope scope;\n\n\tCommit *commit = ObjectWrap::Unwrap(args.This());\n\n\tconst git_tree *tree = git_commit_tree(commit->commit_);\n\n\tTree *treeObject = commit->repository_->wrapTree(const_cast(tree));\n\treturn treeObject->handle_;\n}\n\nHandle Commit::GetParent(const Arguments& args) {\n\tHandleScope scope;\n\n\tCommit *commit = ObjectWrap::Unwrap(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":"\/*\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\nnamespace TLS {\n\nnamespace {\n\nSecureVector strip_leading_zeros(const MemoryRegion& 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 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& 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(2, 1, 65535));\n BigInt g = BigInt::decode(reader.get_range(2, 1, 65535));\n BigInt Y = BigInt::decode(reader.get_range(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 ecdh_key = reader.get_range(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 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(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 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& 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(2, 0, 65535);\n else if(suite.kex_algo() == \"ECDH\")\n key_material = reader.get_range(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\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(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(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}\nFor ECDH you don't strip leading zeros. Bikeshedding: 1 Consistency: 0\/*\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\nnamespace TLS {\n\nnamespace {\n\nSecureVector strip_leading_zeros(const MemoryRegion& 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 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& 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(2, 1, 65535));\n BigInt g = BigInt::decode(reader.get_range(2, 1, 65535));\n BigInt Y = BigInt::decode(reader.get_range(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 ecdh_key = reader.get_range(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 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(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 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& 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(2, 0, 65535);\n else if(suite.kex_algo() == \"ECDH\")\n key_material = reader.get_range(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\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(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(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":"\/* ___\n \/ | |_ _ ___ _ __ __ __ _____\n \/ \/| | | \/ \/ | __\/ \/ \/ \/_____\/\n \/ \/ | | |\/ \/ \/| | | \/ \/_\/ \/__\\ \\\n \/_\/ |_|___\/_\/ |_|_| \\____\/_____\/\n\nCopyright (C) 2019 Jack Steilberg \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}\nAdded resizing for window (buggy)\/* ___\n \/ | |_ _ ___ _ __ __ __ _____\n \/ \/| | | \/ \/ | __\/ \/ \/ \/_____\/\n \/ \/ | | |\/ \/ \/| | | \/ \/_\/ \/__\\ \\\n \/_\/ |_|___\/_\/ |_|_| \\____\/_____\/\n\nCopyright (C) 2019 Jack Steilberg \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":"#define PUGIXML_NO_EXCEPTIONS\n#define PUGIXML_HEADER_ONLY\n\n#include \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 \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 \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 \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 \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 \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 \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 \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}use enum for type check#define PUGIXML_NO_EXCEPTIONS\n#define PUGIXML_HEADER_ONLY\n\n#include \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 \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 \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 \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 \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 \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 \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 \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":"\/*\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 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}\nAdd missing checks for geometry shader stages in GrVkUtil.cpp\/*\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 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":"#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(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(0, programContext->getRefInputBuffer());\n kernel.setArg(1, programContext->getRefOutputBuffer());\n kernel.setArg(2, cdBaseBuffer);\n kernel.setArg(3, resultBuffer);\n kernel.setArg (4, static_cast(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(\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\nFixed a copy-paste mistake.#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(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(0, programContext->getRefInputBuffer());\n kernel.setArg(1, programContext->getRefOutputBuffer());\n kernel.setArg(2, cdBaseBuffer);\n kernel.setArg(3, resultBuffer);\n kernel.setArg (4, static_cast(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(\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":"#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\nComment fix.#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":"#include \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}\nAdd missing include to read.cpp#include \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":"#include \n#include \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}\nAdd features to read binary:#include \n#include \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(in)),\n std::istreambuf_iterator());\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":"\/\/ 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 \n#include \n#include \n#include \n#include \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 SimpleTagHDF5::units() const {\n vector units;\n group().getData(\"units\", units);\n return units;\n}\n\n\nvoid SimpleTagHDF5::units(vector &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 SimpleTagHDF5::position() const {\n vector position;\n group().getData(\"position\", position);\n return position;\n}\n\n\nvoid SimpleTagHDF5::position(const vector &position) {\n group().setData(\"position\", position);\n}\n\n\nvector SimpleTagHDF5::extent() const {\n vector extent;\n group().getData(\"extent\", extent);\n return extent;\n}\n\n\nvoid SimpleTagHDF5::extent(const vector &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 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 &references) {\n vector 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(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(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(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\nModified (optional) getter of entities in \"SimpleTag\" to return empty entity if field missing.\/\/ 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 \n#include \n#include \n#include \n#include \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 SimpleTagHDF5::units() const {\n vector units;\n group().getData(\"units\", units);\n return units;\n}\n\n\nvoid SimpleTagHDF5::units(vector &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 SimpleTagHDF5::position() const {\n vector position;\n group().getData(\"position\", position);\n return position;\n}\n\n\nvoid SimpleTagHDF5::position(const vector &position) {\n group().setData(\"position\", position);\n}\n\n\nvector SimpleTagHDF5::extent() const {\n vector extent;\n group().getData(\"extent\", extent); \n return extent;\n}\n\n\nvoid SimpleTagHDF5::extent(const vector &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 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 &references) {\n vector 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(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(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":"\/*** tws_strat.cpp -- TWS strategy module\n *\n * Copyright (C) 2012 Ruediger Meier\n *\n * Author: Ruediger Meier \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 \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 "e = 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}Strat, don't place new orders if we have that side already\/*** tws_strat.cpp -- TWS strategy module\n *\n * Copyright (C) 2012 Ruediger Meier\n *\n * Author: Ruediger Meier \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 \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 "e = 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":"\/*!\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 \n\nusing namespace intercept::types;\n\nnamespace intercept {\n \/\/! Nular function map.\n typedef std::unordered_map> nular_map;\n \/\/! Unary function map.\n typedef std::unordered_map> unary_map;\n \/\/! Binary functon map.\n typedef std::unordered_map> 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(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 {\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 _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, 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, 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 _scriptTypes;\n map_string_to_class> _scriptFunctions;\n map_string_to_class> _scriptOperators;\n map_string_to_class> _scriptNulars;\n };\n }\n\n}Fix Stuff\/*!\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 \n\nusing namespace intercept::types;\n\nnamespace intercept {\n \/\/! Nular function map.\n typedef std::unordered_map> nular_map;\n \/\/! Unary function map.\n typedef std::unordered_map> unary_map;\n \/\/! Binary functon map.\n typedef std::unordered_map> 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(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 {\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 _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, 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, 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 _scriptTypes;\n map_string_to_class> _scriptFunctions;\n map_string_to_class> _scriptOperators;\n map_string_to_class> _scriptNulars;\n };\n template class rv_allocator;\n template class rv_allocator;\n template class rv_allocator;\n }\n\n}<|endoftext|>"} {"text":"#ifndef IMPL_AX_SYSTEM_HPP\n#define IMPL_AX_SYSTEM_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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;\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 components;\n };\n\n \/\/ A component that store multiple of the same type of component.\n template\n struct multi_component : public ax::component\n {\n CONSTRAINT(multi_component);\n constexpr void static_check() { CONSTRAIN(T, component); }\n ax::vector 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\n class system_t : public ax::system\n {\n public:\n\n CONSTRAINT(system_t);\n using component_t = T;\n template using reify = ax::system_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::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, ax::system);\n\n ax::vector components;\n std::unordered_map component_map;\n std::queue free_list;\n };\n\n template\n class multi_system final : public ax::system_t>\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;\n template using reify = ax::multi_system;\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);\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;\n ENABLE_CAST(multi_system_s_a_n, ax::system_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\n {\n public:\n\n world(\n std::function initialize_systems_impl,\n std::function update_systems_impl,\n std::function clean_up_systems_impl);\n\n template\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>(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>(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\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>(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>(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> systems;\n std::function initialize_systems_impl;\n std::function update_systems_impl;\n std::function 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\n const T* try_get_component(const ax::name& name) const { return world.try_get_component(name, get_address()); }\n\n template\n T* try_get_component(const ax::name& name) { return world.try_get_component(name, get_address()); }\n\n template\n const T& get_component(const ax::name& name) const { return *try_get_component(name); }\n\n template\n T& get_component(const ax::name& name)\n {\n VAR* component_opt = *try_get_component(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\nRenamed multi_system.#ifndef IMPL_AX_SYSTEM_HPP\n#define IMPL_AX_SYSTEM_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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;\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 components;\n };\n\n \/\/ A component that store multiple of the same type of component.\n template\n struct multi_component : public ax::component\n {\n CONSTRAINT(multi_component);\n constexpr void static_check() { CONSTRAIN(T, component); }\n ax::vector 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\n class system_t : public ax::system\n {\n public:\n\n CONSTRAINT(system_t);\n using component_t = T;\n template using reify = ax::system_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::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, ax::system);\n\n ax::vector components;\n std::unordered_map component_map;\n std::queue free_list;\n };\n\n template\n class multi_system_t final : public ax::system_t>\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;\n template using reify = ax::multi_system_t;\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);\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;\n ENABLE_CAST(multi_system_s_a_n, ax::system_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\n {\n public:\n\n world(\n std::function initialize_systems_impl,\n std::function update_systems_impl,\n std::function clean_up_systems_impl);\n\n template\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>(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>(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\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>(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>(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> systems;\n std::function initialize_systems_impl;\n std::function update_systems_impl;\n std::function 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\n const T* try_get_component(const ax::name& name) const { return world.try_get_component(name, get_address()); }\n\n template\n T* try_get_component(const ax::name& name) { return world.try_get_component(name, get_address()); }\n\n template\n const T& get_component(const ax::name& name) const { return *try_get_component(name); }\n\n template\n T& get_component(const ax::name& name)\n {\n VAR* component_opt = *try_get_component(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":"\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 \n\nstruct mock_iocallback_t {\n virtual void on_io_complete(event_t *event) = 0;\n virtual ~mock_iocallback_t() {}\n};\n\ntemplate\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 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__ *\/\nFixing mock io layer to work properly with file permissions and truncation in all cases (db creation, loading existing file, force recreation, etc.)\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 \n\nstruct mock_iocallback_t {\n virtual void on_io_complete(event_t *event) = 0;\n virtual ~mock_iocallback_t() {}\n};\n\ntemplate\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 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":"\/*************************************************************************\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 \n#endif\n#ifndef _VCL_DLLAPI_H\n#include \n#endif\n\n#ifndef _TOOLS_COLOR_HXX\n#include \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\nINTEGRATION: 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.\/*************************************************************************\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 * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SV_WALL_HXX\n#define _SV_WALL_HXX\n\n#include \n#include \n#include \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":"#include \"v8monoctx.h\"\n\nstatic v8::Isolate* isolate;\nstatic v8::Persistent context;\nstatic std::map ScriptModified;\nstatic std::map ScriptCached;\n\nstatic std::string GlobalData;\nstatic std::vector 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 : \"\";\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(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 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& 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& 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 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 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 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 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 source = v8::String::NewFromUtf8(isolate, file_append.c_str());\n\t\tv8::Handle ffn = v8::String::NewFromUtf8(isolate, fname.c_str());\n\n\t\t\/\/ Origin\n\t\tv8::Handle line = v8::Integer::New(isolate, 0);\n\t\tv8::Handle 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(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::New(isolate, ScriptCached[key]);\n\t}\n\n\tv8::Handle 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 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 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 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 source = v8::String::NewFromUtf8(isolate, file_append.c_str());\n\t\tv8::Handle ffn = v8::String::NewFromUtf8(isolate, fname.c_str());\n\n\t\t\/\/ Origin\n\t\tv8::Handle line = v8::Integer::New(isolate, 0);\n\t\tv8::Handle 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(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::New(isolate, ScriptCached[key]);\n\t}\n\n\tv8::Handle 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\nSplit maps#include \"v8monoctx.h\"\n\nstatic v8::Isolate* isolate;\nstatic v8::Persistent context;\n\n\/* maps for caching templates (ExecuteFile) *\/\nstatic std::map ExecuteScriptModified;\nstatic std::map ExecuteScriptCached;\n\n\/* maps for caching utilites (LoadFile) *\/\nstatic std::map LoadScriptModified;\nstatic std::map LoadScriptCached;\n\nstatic std::string GlobalData;\nstatic std::vector 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 : \"\";\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(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 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& 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& 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 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 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 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 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 source = v8::String::NewFromUtf8(isolate, file_append.c_str());\n\t\tv8::Handle ffn = v8::String::NewFromUtf8(isolate, fname.c_str());\n\n\t\t\/\/ Origin\n\t\tv8::Handle line = v8::Integer::New(isolate, 0);\n\t\tv8::Handle 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(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::New(isolate, LoadScriptCached[key]);\n\t}\n\n\tv8::Handle 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 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 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 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 source = v8::String::NewFromUtf8(isolate, file_append.c_str());\n\t\tv8::Handle ffn = v8::String::NewFromUtf8(isolate, fname.c_str());\n\n\t\t\/\/ Origin\n\t\tv8::Handle line = v8::Integer::New(isolate, 0);\n\t\tv8::Handle 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(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::New(isolate, ExecuteScriptCached[key]);\n\t}\n\n\tv8::Handle 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":"\/*\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 \n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include \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 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();\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(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional 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();\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();\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();\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(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional 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();\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(ret);\n\t}\n\n\ttypedef std::pair 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 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}\nadded MooPolice client identification\/*\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 \n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include \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 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();\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(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional 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();\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();\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();\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(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional 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();\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(ret);\n\t}\n\n\ttypedef std::pair 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 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":"\/*\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 \n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include \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 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();\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(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional 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();\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();\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();\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(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional 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();\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(ret);\n\t}\n\n\ttypedef std::pair 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 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*** empty log message ***\/*\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 \n#include \n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include \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 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();\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(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional 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();\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();\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();\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(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional 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();\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(ret);\n\t}\n\n\ttypedef std::pair 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 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":"\/*\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 \n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include \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 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();\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();\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();\n\t\tret.major_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\tret.minor_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\tret.revision_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\tret.tag_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional();\n\n\t\treturn boost::optional(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional 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();\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();\n\t\t\tret.major_version = *i - '0';\n\t\t\t++i;\n\n\t\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\t\tret.minor_version = *i - '0';\n\t\t\t++i;\n\n\t\t\tif (!std::isdigit(*i)) return boost::optional();\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();\n\t\t\tret.major_version = *i;\n\t\t\t++i;\n\n\t\t\tif (*i > 127) return boost::optional();\n\t\t\tret.minor_version = *i;\n\t\t\t++i;\n\n\t\t\tif (*i > 127) return boost::optional();\n\t\t\tret.revision_version = *i;\n\t\t}\n\t\telse\n\t\t\treturn boost::optional();\n\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional 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();\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();\n\t\tret.major_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional();\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\tret.minor_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional();\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\tret.revision_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::equal(i, i+1, \"--\")) return boost::optional();\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional(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 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*** empty log message ***\/*\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 \n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include \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 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();\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();\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();\n\t\tret.major_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\tret.minor_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\tret.revision_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\tret.tag_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional();\n\n\t\treturn boost::optional(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a shadow-style\n\t\/\/ identification\n\tboost::optional 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();\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();\n\t\t\tret.major_version = *i - '0';\n\t\t\t++i;\n\n\t\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\t\tret.minor_version = *i - '0';\n\t\t\t++i;\n\n\t\t\tif (!std::isdigit(*i)) return boost::optional();\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();\n\t\t\tret.major_version = *i;\n\t\t\t++i;\n\n\t\t\tif (*i > 127) return boost::optional();\n\t\t\tret.minor_version = *i;\n\t\t\t++i;\n\n\t\t\tif (*i > 127) return boost::optional();\n\t\t\tret.revision_version = *i;\n\t\t}\n\t\telse\n\t\t\treturn boost::optional();\n\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional(ret);\n\t}\n\n\t\/\/ checks if a peer id can possibly contain a mainline-style\n\t\/\/ identification\n\tboost::optional 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();\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();\n\t\tret.major_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional();\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\tret.minor_version = *i - '0';\n\t\t++i;\n\n\t\tif (*i != '-') return boost::optional();\n\t\t++i;\n\n\t\tif (!std::isdigit(*i)) return boost::optional();\n\t\tret.revision_version = *i - '0';\n\t\t++i;\n\n\t\tif (!std::equal(i, i+1, \"--\")) return boost::optional();\n\n\t\tret.tag_version = 0;\n\t\treturn boost::optional(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 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":"#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 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 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(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(new Way());\n setCoordinates(*way, polyNode->Contour);\n newRelation.elements.push_back(way);\n }\n else {\n std::shared_ptr 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\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\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, path);\n }\n\n template\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}}\nrefactoring: adjust code style#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 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 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(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(new Way());\n setCoordinates(*way, polyNode->Contour);\n newRelation.elements.push_back(way);\n }\n else {\n std::shared_ptr 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\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\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, path);\n }\n\n template\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":"\/**\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\nclass Fiber {\npublic:\n \/**\n * Constructor.\n *\/\n Fiber(const Shared>& state = nullptr);\n\n \/**\n * Clone the fiber.\n *\/\n Fiber 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> state;\n};\n}\n\ntemplate\nlibbirch::Fiber::Fiber(\n const Shared>& state) :\n state(state) {\n \/\/\n}\n\ntemplate\nlibbirch::Fiber libbirch::Fiber::clone() const {\n return Fiber(state.clone());\n}\n\ntemplate\nvoid libbirch::Fiber::freeze() const {\n state.freeze();\n}\n\ntemplate\nlibbirch::Context* libbirch::Fiber::getContext() const {\n return state.getContext();\n}\n\ntemplate\nbool libbirch::Fiber::query() const {\n bool result = false;\n if (state.query()) {\n result = state->query();\n if (!result) {\n const_cast*>(this)->state = nullptr; \/\/ fiber has finished, delete the state\n }\n }\n return result;\n}\n\ntemplate\nYieldType libbirch::Fiber::get() const {\n libbirch_assert_msg_(state.query(), \"fiber handle undefined\");\n return state->get();\n}\nAdded finish() to Fiber.\/**\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\nclass Fiber {\npublic:\n \/**\n * Constructor.\n *\/\n Fiber(const Shared>& state = nullptr);\n\n \/**\n * Clone the fiber.\n *\/\n Fiber 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> state;\n};\n}\n\ntemplate\nlibbirch::Fiber::Fiber(\n const Shared>& state) :\n state(state) {\n \/\/\n}\n\ntemplate\nlibbirch::Fiber libbirch::Fiber::clone() const {\n return Fiber(state.clone());\n}\n\ntemplate\nvoid libbirch::Fiber::freeze() const {\n state.freeze();\n}\n\ntemplate\nvoid libbirch::Fiber::finish() const {\n state.finish();\n}\n\ntemplate\nlibbirch::Context* libbirch::Fiber::getContext() const {\n return state.getContext();\n}\n\ntemplate\nbool libbirch::Fiber::query() const {\n bool result = false;\n if (state.query()) {\n result = state->query();\n if (!result) {\n const_cast*>(this)->state = nullptr; \/\/ fiber has finished, delete the state\n }\n }\n return result;\n}\n\ntemplate\nYieldType libbirch::Fiber::get() const {\n libbirch_assert_msg_(state.query(), \"fiber handle undefined\");\n return state->get();\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * Copyright (C) 2011-2013 Michael Krufky\n *\n * Author: Michael Krufky \n *\n * This 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 \n#include \n#include \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}\ndesc: don't process descriptor data if decoder failed\/*****************************************************************************\n * Copyright (C) 2011-2013 Michael Krufky\n *\n * Author: Michael Krufky \n *\n * This 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 \n#include \n#include \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":"\/\/\n\/\/ Created by Nick on 27.03.16.\n\/\/\n\nAdd some simple tests#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 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 m;\n jstp::JSRS t1(25.5);\n jstp::JSRS t2(true);\n jstp::JSRS t3(\"test\");\n std::vector 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":"#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 > 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 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::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 object, void *parameter){\n\tbyPtr.erase(static_cast(parameter));\n\tobject.Dispose();\n\tobject.Clear();\n\tDEBUG_LOG(\"Removed cached device %p\", parameter);\n}\n\nstatic Handle 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 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 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 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 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 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 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 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 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 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 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 callback;\n\tint errcode;\n\n\tvoid submit(Device* d, Handle cb, uv_work_cb backend, uv_work_cb after){\n\t\tcallback = Persistent::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::New(baton->device->handle_);\n\t\tbaton->device->unref();\n\n\t\tif (!baton->callback.IsEmpty()) {\n\t\t\tHandle 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 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 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 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 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 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 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 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 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 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 pDevice(\"Device\", &init);\nExpose endpoint descriptor's wMaxPacketSize.#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 > 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 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::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 object, void *parameter){\n\tbyPtr.erase(static_cast(parameter));\n\tobject.Dispose();\n\tobject.Clear();\n\tDEBUG_LOG(\"Removed cached device %p\", parameter);\n}\n\nstatic Handle 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 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 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 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 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 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 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 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 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 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 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 callback;\n\tint errcode;\n\n\tvoid submit(Device* d, Handle cb, uv_work_cb backend, uv_work_cb after){\n\t\tcallback = Persistent::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::New(baton->device->handle_);\n\t\tbaton->device->unref();\n\n\t\tif (!baton->callback.IsEmpty()) {\n\t\t\tHandle 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 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 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 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 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 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 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 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 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 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 pDevice(\"Device\", &init);\n<|endoftext|>"} {"text":"\/******************************************************************************\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 \n\n#include \"modules\/planning\/common\/speed\/st_point.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace {\nconstexpr double kInf = std::numeric_limits::infinity();\n}\n\nDpStCost::DpStCost(const DpStSpeedConfig& config,\n const std::vector& 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\nPlanning: added default obstacle cost for overtake. (#2207)\/******************************************************************************\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 \n\n#include \"modules\/planning\/common\/speed\/st_point.h\"\n\nnamespace apollo {\nnamespace planning {\nnamespace {\nconstexpr double kInf = std::numeric_limits::infinity();\n}\n\nDpStCost::DpStCost(const DpStSpeedConfig& config,\n const std::vector& 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":"\/*\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__\nbase: Defining make_unique for C++11\/*\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 \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\nstd::unique_ptr\nmake_unique( Args&&... constructor_args )\n{\n return std::unique_ptr(\n new T( std::forward(constructor_args)... )\n );\n}\n\n#endif \/\/ __cplusplus == 201402L\n\n} \/\/namespace m5\n\n#endif \/\/ __BASE_COMPILER_HH__\n<|endoftext|>"} {"text":"\/\/ 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 \n#endif\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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 \nT GetTime()\n{\n const std::chrono::seconds mocktime(nMockTime);\n\n return std::chrono::duration_cast(\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}\nTweak exception handling in MilliTimer class to eliminate compiler warnings\/\/ 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 \n#endif\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \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 \nT GetTime()\n{\n const std::chrono::seconds mocktime(nMockTime);\n\n return std::chrono::duration_cast(\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":"\/\/ 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 \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \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 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(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 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 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 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 &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 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 &unitsA, const vector &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 &unitsA, const vector &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\nFixes to match validation branch\/\/ 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 \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \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 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(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 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 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 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 &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 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 &unitsA, const vector &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 &unitsA, const vector &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":"\/\/ Day04.cpp : This file contains the 'main' function. Program execution begins and ends there.\n\/\/\n\n#include \"pch.h\"\n\ntypedef std::array 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 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}\nDay 04 part two\/\/ Day04.cpp : This file contains the 'main' function. Program execution begins and ends there.\n\/\/\n\n#include \"pch.h\"\n\ntypedef std::array 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 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":"\/\/ @(#)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; iNDaughters(); 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\nInitialize all members of TParticlePDG in the constructors. Non set members were given problems with I\/O.\/\/ @(#)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; iNDaughters(); 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":"\/*\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 \n#include \n#include \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> 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; iUpdate MinSpanTree.cpp\/*\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 \n#include \n#include \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> 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"} {"text":"#include \"libs\/base\/httpd.h\"\n\n#include \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 \nvoid* TaggedPointer(T* p) {\n assert((reinterpret_cast(p) & kTagMask) == 0);\n return reinterpret_cast(reinterpret_cast(p) | Tag);\n}\n\nintptr_t Tag(void* p) { return reinterpret_cast(p) & kTagMask; }\n\ntemplate \nT* Pointer(void* p) {\n return reinterpret_cast(reinterpret_cast(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(&content)) {\n auto file_holder = std::make_unique();\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(file_holder.release());\n return 1;\n }\n }\n\n if (auto* static_buffer = std::get_if(&content)) {\n file->data = reinterpret_cast(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>(&content)) {\n file->data = reinterpret_cast(v->data());\n file->len = v->size();\n file->index = file->len;\n file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;\n file->pextension = TaggedPointer(\n new std::vector(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(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(file->pextension);\n } else if (tag == kTagVector) {\n delete Pointer>(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\nFix dynamic buffer serve#include \"libs\/base\/httpd.h\"\n\n#include \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 \nvoid* TaggedPointer(T* p) {\n assert((reinterpret_cast(p) & kTagMask) == 0);\n return reinterpret_cast(reinterpret_cast(p) | Tag);\n}\n\nintptr_t Tag(void* p) { return reinterpret_cast(p) & kTagMask; }\n\ntemplate \nT* Pointer(void* p) {\n return reinterpret_cast(reinterpret_cast(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(&content)) {\n auto file_holder = std::make_unique();\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(file_holder.release());\n return 1;\n }\n }\n\n if (auto* static_buffer = std::get_if(&content)) {\n file->data = reinterpret_cast(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>(&content)) {\n file->data = reinterpret_cast(v->data());\n file->len = v->size();\n file->index = 0;\n file->flags = FS_FILE_FLAGS_HEADER_PERSISTENT;\n file->pextension = TaggedPointer(\n new std::vector(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(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>(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(file->pextension);\n } else if (tag == kTagVector) {\n delete Pointer>(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":"\/******************************************************************************\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 \n#include \n#include \n#include \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, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\n\/\/ template class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\n#endif\n#ifndef SOFA_FLOAT\n#ifndef SOFA_DOUBLE\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\n\/\/ template class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\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, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n\/\/ .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n#endif\n#ifndef SOFA_FLOAT\n#ifndef SOFA_DOUBLE\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n\/\/ .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n#endif\n#endif\n\n\n\/\/ #ifdef SOFA_GPU_CUDA_DOUBLE\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n\/\/ .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n\/\/\n\/\/ .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n\/\/ .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n\/\/ #endif\n ;\n\n} \/\/ namespace cuda\n\n} \/\/ namespace gpu\n\n} \/\/ namespace sofa\nr6716\/sofa-dev : Add cuda template for CudaBarycentricMapping\/******************************************************************************\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 \n#include \n#include \n#include \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, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\n\/\/ template class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\n#endif\n#ifndef SOFA_FLOAT\n#ifndef SOFA_DOUBLE\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\ntemplate class BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > >;\n\/\/ template class BarycentricMapping< Mapping< State, MappedModel > >;\ntemplate class BarycentricMapping< Mapping< State, MappedModel > >;\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, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n\/\/ .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n#endif\n#ifndef SOFA_FLOAT\n#ifndef SOFA_DOUBLE\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n\/\/ .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n .add< BarycentricMapping< Mapping< State, MappedModel > > >()\n#endif\n#endif\n\n\n#ifdef SOFA_GPU_CUDA_DOUBLE\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n .add< BarycentricMapping< MechanicalMapping< MechanicalState, MechanicalState > > >()\n\/\/.add< BarycentricMapping< Mapping< State, MappedModel > > >()\n\/\/.add< BarycentricMapping< Mapping< State, MappedModel > > >()\n#endif\n ;\n\n} \/\/ namespace cuda\n\n} \/\/ namespace gpu\n\n} \/\/ namespace sofa\n<|endoftext|>"} {"text":"#include \n\nstd::string colorToString(const sf::Color& color) {\n std::stringstream ret;\n ret << \"(\"\n << static_cast(color.r) << \", \"\n << static_cast(color.g) << \", \"\n << static_cast(color.b) << \", \"\n << static_cast(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(255);\n auto g = node[1].as(255);\n auto b = node[2].as(255);\n auto a = node[3].as(255);\n\n return sf::Color(\n static_cast(r),\n static_cast(g),\n static_cast(b),\n static_cast(a)\n );\n}\n\nsf::Vertex nodeToVertex(const YAML::Node& node, int size) {\n auto x = node[0].as() * size \/ 2;\n auto y = node[1].as() * size \/ 2;\n\n return sf::Vertex(sf::Vector2f(x, y));\n}\nBetter handle bad data in entity color definitions. Also C++-ify the function.#include \n\nstd::string colorToString(const sf::Color& color) {\n std::stringstream ret;\n ret << \"(\"\n << static_cast(color.r) << \", \"\n << static_cast(color.g) << \", \"\n << static_cast(color.b) << \", \"\n << static_cast(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 color = {255, 255, 255, 255};\n\n uint8_t i = 0;\n for (auto&& primary : color) {\n auto newPrimary = node[i++].as(255);\n if (newPrimary > 255) {\n newPrimary = 255;\n }\n primary = static_cast(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() * size \/ 2;\n auto y = node[1].as() * size \/ 2;\n\n return sf::Vertex(sf::Vector2f(x, y));\n}\n<|endoftext|>"} {"text":"Server: Set app name<|endoftext|>"} {"text":"#pragma once\n\n\/\/#define BOOST_VARIANT_MINIMIZE_SIZE 1\n#include \"boost\/variant.hpp\"\n#include \"boost\/optional.hpp\"\n\n#include \n#include \n#include \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;\n\n\/**\n * Array type.\n *\/\nusing array_type = std::list;\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;\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\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\n boost::optional get(const std::initializer_list& path) {\n auto node = this;\n for (auto name : path) {\n if (node->x.type() == typeid(object_type)) {\n auto& o = boost::get(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();\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\n boost::optional get(\n const std::initializer_list& path) const {\n auto node = this;\n for (auto name : path) {\n if (node->x.type() == typeid(object_type)) {\n auto& o = boost::get(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();\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\n boost::optional get(const std::string& name) {\n if (x.type() == typeid(object_type)) {\n auto& o = boost::get(x);\n auto iter = o.find(name);\n if (iter != o.end()) {\n return iter->second.get();\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\n boost::optional get(const std::string& name) const {\n if (x.type() == typeid(object_type)) {\n auto& o = boost::get(x);\n auto iter = o.find(name);\n if (iter != o.end()) {\n return iter->second.get();\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\n boost::optional get() {\n if (x.type() == typeid(T)) {\n return boost::get(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\n boost::optional get() const {\n if (x.type() == typeid(T)) {\n return boost::get(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 get(\n const std::initializer_list& 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 get(\n const std::initializer_list& 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 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 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& 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}\nArray type is now std::vector not std::list, to facilitate random access required by fiber iterators in Birch standard library.#pragma once\n\n\/\/#define BOOST_VARIANT_MINIMIZE_SIZE 1\n#include \"boost\/variant.hpp\"\n#include \"boost\/optional.hpp\"\n\n#include \n#include \n#include \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;\n\n\/**\n * Array type.\n *\/\nusing array_type = std::vector;\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;\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\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\n boost::optional get(const std::initializer_list& path) {\n auto node = this;\n for (auto name : path) {\n if (node->x.type() == typeid(object_type)) {\n auto& o = boost::get(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();\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\n boost::optional get(\n const std::initializer_list& path) const {\n auto node = this;\n for (auto name : path) {\n if (node->x.type() == typeid(object_type)) {\n auto& o = boost::get(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();\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\n boost::optional get(const std::string& name) {\n if (x.type() == typeid(object_type)) {\n auto& o = boost::get(x);\n auto iter = o.find(name);\n if (iter != o.end()) {\n return iter->second.get();\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\n boost::optional get(const std::string& name) const {\n if (x.type() == typeid(object_type)) {\n auto& o = boost::get(x);\n auto iter = o.find(name);\n if (iter != o.end()) {\n return iter->second.get();\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\n boost::optional get() {\n if (x.type() == typeid(T)) {\n return boost::get(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\n boost::optional get() const {\n if (x.type() == typeid(T)) {\n return boost::get(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 get(\n const std::initializer_list& 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 get(\n const std::initializer_list& 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 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 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& 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":"\/*\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 \n#include \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(i, 0));\n }\n }\n\n return mShareID++;\n}\n\n\nFix BMC#16089 - Fix return value of GetCredsState implementation Signed-off-by: James Ausmus \/*\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 \n#include \n\n#include \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(i, 0));\n }\n }\n\n return mShareID++;\n}\n\n\n<|endoftext|>"} {"text":"#include \"zip.h\"\n\n#include \/\/ std::search\n#include \n#include \n#include \n#include \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 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\nZIP: switch to store if deflate makes file larger #16#include \"zip.h\"\n\n#include \/\/ std::search\n#include \n#include \n#include \n#include \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 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":"Minor change to FIXME comment<|endoftext|>"} {"text":"#ifndef _SNARKFRONT_AES_KEY_EXPANSION_HPP_\n#define _SNARKFRONT_AES_KEY_EXPANSION_HPP_\n\n#include \n#include \n\n#include \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 \nclass AES_KeyExpansion\n{\npublic:\n typedef VAR VarType;\n\n typedef std::array Key128Type;\n typedef std::array Key192Type;\n typedef std::array Key256Type;\n\n typedef std::array Schedule128Type;\n typedef std::array Schedule192Type;\n typedef std::array Schedule256Type;\n\n AES_KeyExpansion() = default;\n\n \/\/ AES-128\n void operator() (const std::array& key,\n std::array& w) const {\n expand(key, w);\n }\n\n \/\/ AES-192\n void operator() (const std::array& key,\n std::array& w) const {\n expand(key, w);\n }\n\n \/\/ AES-256\n void operator() (const std::array& key,\n std::array& 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 \n void expand(const std::array& key, \/\/ 4 * Nk octets\n std::array& 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 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 m_sbox;\n};\n\n} \/\/ namespace snarkfront\n\n#endif\nDelete AES_KeyExpansion.hpp<|endoftext|>"} {"text":"#include \"amici\/edata.h\"\n\n#include \"amici\/defines.h\"\n#include \"amici\/model.h\"\n\n#include \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(nt * nytrue),\n std::vector(nt * nytrue),\n std::vector(nmaxevent * nztrue),\n std::vector(nmaxevent * nztrue))\n\n{\n}\n\nExpData::ExpData(int nytrue, int nztrue, int nt, int nmaxevent,\n const std::vector &my,\n const std::vector &sigmay,\n const std::vector &mz,\n const std::vector &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 my;\n\/\/ \/** standard deviation of observed data (dimension: nt x nytrue, row-major) *\/\n\/\/ std::vector sigmay;\n\n\/\/ \/** observed events (dimension: nmaxevents x nztrue, row-major) *\/\n\/\/ std::vector mz;\n\/\/ \/** standard deviation of observed events\/roots\n\/\/ * (dimension: nmaxevents x nztrue, row-major)*\/\n\/\/ std::vector 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(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(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(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(observedEventsStdDev[imz]);\n }\n}\n\nExpData::~ExpData() {\n}\n\n} \/\/ namespace amici\nCleanup#include \"amici\/edata.h\"\n\n#include \"amici\/defines.h\"\n#include \"amici\/model.h\"\n\n#include \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(nt * nytrue),\n std::vector(nt * nytrue),\n std::vector(nmaxevent * nztrue),\n std::vector(nmaxevent * nztrue))\n\n{\n}\n\nExpData::ExpData(int nytrue, int nztrue, int nt, int nmaxevent,\n const std::vector &my,\n const std::vector &sigmay,\n const std::vector &mz,\n const std::vector &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(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(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(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(observedEventsStdDev[imz]);\n }\n}\n\nExpData::~ExpData() {\n}\n\n} \/\/ namespace amici\n<|endoftext|>"} {"text":"\/\/ 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(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(®ionIndexCount)) {\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(®ionIndex) || 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 ®ionCount)) {\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 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 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[variations] ignore VarRegionList.RegionAxisCount when RegionCount == 0\/\/ 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(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(®ionIndexCount)) {\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(®ionIndex) || 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 ®ionCount)) {\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 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 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":"lb_http: implement class Cancellable<|endoftext|>"} {"text":"fix noise on mobile<|endoftext|>"} {"text":"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}\nReally fix enemy movement this timevoid 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":"\/*\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 \n# include \n# include \n\n# include \n# include \n# include \n# include \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 \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 unbind_type;\n unbind_type unbind_;\n\n \/\/\/ Declaration * (routine_depth * scope_depth)\n typedef std::pair > binding_type;\n typedef std::list Bindings;\n typedef std::map Environment;\n \/\/\/ Map of currently bound variables\n Environment env_;\n\n \/\/\/ Whether to apply setSlot on self\n typedef std::vector 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 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 \n\n#endif \/\/ !BINDER_BINDER_HH\nbind: use hash table.\/*\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 \n# include \n# include \n\n# include \n# include \n# include \n# include \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 \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 unbind_type;\n unbind_type unbind_;\n\n \/\/\/ Declaration * (routine_depth * scope_depth)\n typedef std::pair > binding_type;\n typedef std::list Bindings;\n typedef boost::unordered_map Environment;\n \/\/\/ Map of currently bound variables\n Environment env_;\n\n \/\/\/ Whether to apply setSlot on self\n typedef std::vector 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 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 \n\n#endif \/\/ !BINDER_BINDER_HH\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) <2002-2006> \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 \n#include \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\nStarted the 0.7.1 development\/*\n * Copyright (c) <2002-2006> \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 \n#include \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":"\/**\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 .\n *\/\n#include \n\n#include \n#include \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\nRefine error text mapping.\/**\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 .\n *\/\n#include \n\n#include \n#include \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":"Play with elastic<|endoftext|>"} {"text":"\/*******************************************************************************\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 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 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}\nfixed addevent\/*******************************************************************************\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 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 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":"\/*\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 \n#include \n#include \n\n\/\/ General Libraries\n#include \n\n\/\/ DataType libraries\n#include \n#include \n\n\/\/ Tikhonov specific\n#include \n#include \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}\nstarted adding functional tests. need to figure how to extract results\/*\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 \n#include \n#include \n\n\/\/ General Libraries\n#include \n\n\/\/ DataType libraries\n#include \n#include \n\n\/\/ Tikhonov specific\n#include \n#include \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":"Disable line smoothing in plotter on GLES<|endoftext|>"} {"text":"#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\nSignal the exception properly#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":"\n\/**\n * This file is part of the boostcache package.\n *\n * (c) Azat Khuzhin \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 \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}[kernel\/commands] add ADD_COMMAND() macros to avoid long lines.\n\/**\n * This file is part of the boostcache package.\n *\n * (c) Azat Khuzhin \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 \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":"\/\/ TODO: resolve after importing Oniguruma from MRI\n#include \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(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(\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(\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();\n\n switch(TYPE(obj)) {\n case T_ENCODING:\n enc = c_as(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(\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(val)) {\n str->encoding(env->state(), enc);\n } else if(Regexp* reg = try_as(val)) {\n reg->encoding(env->state(), enc);\n } else if(Symbol* sym = try_as(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}\nFixed rb_enc_compatible.\/\/ TODO: resolve after importing Oniguruma from MRI\n#include \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(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(\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(\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();\n\n switch(TYPE(obj)) {\n case T_ENCODING:\n enc = c_as(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(\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(val)) {\n str->encoding(env->state(), enc);\n } else if(Regexp* reg = try_as(val)) {\n reg->encoding(env->state(), enc);\n } else if(Symbol* sym = try_as(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":"\/*\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 \n#include \n#include \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(counter + load_be(&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(&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(&m_counter[off], 0);\n uint64_t b1 = load_be(&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(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(m_counter[off]) + carry;\n m_counter[off] = static_cast(cnt);\n local_counter = (local_counter >> 8);\n carry = (cnt >> 8) + static_cast(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(&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(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}\nAvoid pointless write\/*\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 \n#include \n#include \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(counter + load_be(&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(&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(&m_counter[off], 0);\n uint64_t b1 = load_be(&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(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(m_counter[off]) + carry;\n m_counter[off] = static_cast(cnt);\n local_counter = (local_counter >> 8);\n carry = (cnt >> 8) + static_cast(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(&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(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":"Fix use of or<|endoftext|>"} {"text":"\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 \n#include \n#include \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\nFix display driver initialization bug\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 \n#include \n#include \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":"\/*\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 \n\nusing namespace tiny_dnn;\nusing namespace tiny_dnn::layers;\nusing namespace tiny_dnn::activation;\n\nstatic void construct_net( network &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 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 train_labels, test_labels;\n std::vector 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( 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( 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- messed up up with the args management.\/*\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 \n\nusing namespace tiny_dnn;\nusing namespace tiny_dnn::layers;\nusing namespace tiny_dnn::activation;\n\nstatic void construct_net( network &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 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 train_labels, test_labels;\n std::vector 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( 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( 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":"\/*\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 \n#include \n#include \n\n#include \"reductions.h\"\n#include \"vw.h\"\n\nnamespace TOPK {\n typedef pair > 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, compare_scored_examples > pr_queue;\n vw* all;\n };\n\n void print_result(int f, priority_queue, 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 \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(), \"top k recommendation\");\n if(missing_required(all)) return NULL;\n\n topk& data = calloc_or_die();\n data.B = (uint32_t)all.vm[\"top\"].as();\n data.all = &all;\n\n LEARNER::learner& l = init_learner(&data, setup_base(all), predict_or_learn, \n\t\t\t\t\t predict_or_learn);\n l.set_finish_example(finish_example);\n\n return make_base(l);\n }\n}\ntopk simplifications\/*\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 \n#include \n\n#include \"reductions.h\"\n#include \"vw.h\"\n\nnamespace TOPK {\n typedef pair > 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, compare_scored_examples > pr_queue;\n };\n\n void print_result(int f, priority_queue, 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 \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(), \"top k recommendation\");\n if(missing_required(all)) return NULL;\n\n topk& data = calloc_or_die();\n data.B = (uint32_t)all.vm[\"top\"].as();\n\n LEARNER::learner& l = init_learner(&data, setup_base(all), predict_or_learn, \n\t\t\t\t\t predict_or_learn);\n l.set_finish_example(finish_example);\n\n return make_base(l);\n }\n}\n<|endoftext|>"} {"text":"src: reading\/owner\/onread\/onconnection for tcp<|endoftext|>"} {"text":"update uoj8581<|endoftext|>"} {"text":"#include \"apps_starter.h\"\n\nstd::vector 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::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 \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}Перевод на новое окно#include \"apps_starter.h\"\n\nstd::vector 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::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 \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":"#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 \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 renderToPixmap();\n virtual ref 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::create(int width, int height) {\n ref 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::load(upath filename) {\n ref 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 YImageGDK::scale(int w, int h) {\n ref 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::createFromPixmap(ref pixmap) {\n return createFromPixmapAndMask(pixmap->pixmap(),\n pixmap->mask(),\n pixmap->width(),\n pixmap->height());\n}\n\nref YImage::createFromPixmapAndMask(Pixmap pixmap, Pixmap mask,\n int width, int height)\n{\n ref 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::createFromIconProperty(long *prop_pixels,\n int width, int height)\n{\n ref 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::createFromPixmapAndMaskScaled(Pixmap pix, Pixmap mask,\n int width, int height,\n int nw, int nh)\n{\n ref image = createFromPixmapAndMask(pix, mask, width, height);\n if (image != null)\n image = image->scale(nw, nh);\n return image;\n}\n\nref 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 YImage::createPixmap(Pixmap pixmap, Pixmap mask, int w, int h) {\n ref 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\nalways use compositing for image drawing#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 \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 renderToPixmap();\n virtual ref 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::create(int width, int height) {\n ref 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::load(upath filename) {\n ref 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 YImageGDK::scale(int w, int h) {\n ref 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::createFromPixmap(ref pixmap) {\n return createFromPixmapAndMask(pixmap->pixmap(),\n pixmap->mask(),\n pixmap->width(),\n pixmap->height());\n}\n\nref YImage::createFromPixmapAndMask(Pixmap pixmap, Pixmap mask,\n int width, int height)\n{\n ref 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::createFromIconProperty(long *prop_pixels,\n int width, int height)\n{\n ref 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::createFromPixmapAndMaskScaled(Pixmap pix, Pixmap mask,\n int width, int height,\n int nw, int nh)\n{\n ref image = createFromPixmapAndMask(pix, mask, width, height);\n if (image != null)\n image = image->scale(nw, nh);\n return image;\n}\n\nref 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 YImage::createPixmap(Pixmap pixmap, Pixmap mask, int w, int h) {\n ref 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":"\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}\nFix bug where insertEntry() was not incrementing the counter of the number of entries.\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":"HasteMonster-wands now IDs on hit<|endoftext|>"} {"text":"#include \"cap2.h\"\n#include \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}\nDelete main.cpp<|endoftext|>"} {"text":"\/\/ Ouzel by Elviss Strazdins\n\n#ifndef OUZEL_SCENE_CAMERA_HPP\n#define OUZEL_SCENE_CAMERA_HPP\n\n#include \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& initProjection);\n explicit Camera(const math::Size& initTargetContentSize = math::Size{}, 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& newProjection) { projection = newProjection; }\n void recalculateProjection();\n\n const math::Matrix& getViewProjection() const;\n const math::Matrix& getRenderViewProjection() const;\n const math::Matrix& getInverseViewProjection() const;\n\n math::Vector convertNormalizedToWorld(const math::Vector& normalizedPosition) const;\n math::Vector convertWorldToNormalized(const math::Vector& worldPosition) const;\n\n bool checkVisibility(const math::Matrix& boxTransform, const math::Box& 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& 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& 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 \/ 6.0F;\n float nearPlane = 1.0F;\n float farPlane = 100.0F;\n\n math::Matrix projection;\n\n math::Rect viewport = math::Rect{0.0F, 0.0F, 1.0F, 1.0F};\n math::Rect renderViewport;\n math::Size targetContentSize;\n\n ScaleMode scaleMode = ScaleMode::noScale;\n math::Size contentSize{};\n math::Vector contentScale{};\n math::Vector contentPosition{};\n\n bool depthTest = false;\n bool wireframe = false;\n\n mutable bool viewProjectionDirty = true;\n mutable math::Matrix viewProjection;\n mutable math::Matrix renderViewProjection;\n\n mutable bool inverseViewProjectionDirty = true;\n mutable math::Matrix inverseViewProjection;\n\n graphics::RenderTarget* renderTarget = nullptr;\n std::unique_ptr 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\nRecalculate projection on projection parameter change\/\/ Ouzel by Elviss Strazdins\n\n#ifndef OUZEL_SCENE_CAMERA_HPP\n#define OUZEL_SCENE_CAMERA_HPP\n\n#include \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& initProjection);\n explicit Camera(const math::Size& initTargetContentSize = math::Size{}, 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& newProjection)\n {\n projection = newProjection;\n recalculateProjection();\n }\n void recalculateProjection();\n\n const math::Matrix& getViewProjection() const;\n const math::Matrix& getRenderViewProjection() const;\n const math::Matrix& getInverseViewProjection() const;\n\n math::Vector convertNormalizedToWorld(const math::Vector& normalizedPosition) const;\n math::Vector convertWorldToNormalized(const math::Vector& worldPosition) const;\n\n bool checkVisibility(const math::Matrix& boxTransform, const math::Box& box) const;\n\n [[nodiscard]] auto& getViewport() const noexcept { return viewport; }\n void setViewport(const math::Rect& 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& 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 \/ 6.0F;\n float nearPlane = 1.0F;\n float farPlane = 100.0F;\n\n math::Matrix projection;\n\n math::Rect viewport = math::Rect{0.0F, 0.0F, 1.0F, 1.0F};\n math::Rect renderViewport;\n math::Size targetContentSize;\n\n ScaleMode scaleMode = ScaleMode::noScale;\n math::Size contentSize{};\n math::Vector contentScale{};\n math::Vector contentPosition{};\n\n bool depthTest = false;\n bool wireframe = false;\n\n mutable bool viewProjectionDirty = true;\n mutable math::Matrix viewProjection;\n mutable math::Matrix renderViewProjection;\n\n mutable bool inverseViewProjectionDirty = true;\n mutable math::Matrix inverseViewProjection;\n\n graphics::RenderTarget* renderTarget = nullptr;\n std::unique_ptr 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":"\/*\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 .\n*\/\n\n#include \"agent.hh\"\n#include \"mediarelay.hh\"\n\n#include \n\n#include \n#include \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());\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::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();ifillPollFd(&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();iisUsed()){\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}\nfix stack overflow\/*\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 .\n*\/\n\n#include \"agent.hh\"\n#include \"mediarelay.hh\"\n\n#include \n\n#include \n#include \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());\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::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();ifillPollFd(&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();iisUsed()){\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":"\/\/ -*- 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 \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 \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 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 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::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 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 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}\nceph-authtool: make error msg more helpful\/\/ -*- 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 \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 \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 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 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::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 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 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":"\/*\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 \n#include \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(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(), 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() + 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() + 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(),\n (min(func_end, val_end) - func_start) + 1);\n } else {\n \/\/ val_start > func_start\n memcpy(data, getPtr() - 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}\nPacket: Remove meaningless assert statement\/*\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 \n#include \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(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(), 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() + 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() + 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(),\n (min(func_end, val_end) - func_start) + 1);\n } else {\n \/\/ val_start > func_start\n memcpy(data, getPtr() - 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":"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\nVM: Refactor assert.hpp to Factor stylenamespace 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":"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#<|endoftext|>"} {"text":"#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 \n\nBitmap *Menu::work = Bitmap::Screen;\n\nstatic std::string lastPlayed = \"\";\n\nstatic std::queue 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: \"<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 ::iterator b = menuOptions.begin();\n\t\t\t\tstd::vector ::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 ::iterator b = menuOptions.begin();\n\t\t\t\tstd::vector ::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 ::iterator b = menuOptions.begin();\n\tstd::vector ::iterator e = menuOptions.end();\n\tfor(;b!=e;++b)\n\t{\n\t\tif((*b))delete (*b);\n\t}\n}\n\nmenu backgrounds#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 \n\nBitmap *Menu::work = Bitmap::Screen;\n\nstatic std::string lastPlayed = \"\";\n\nstatic std::queue 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: \"<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 ::iterator b = menuOptions.begin();\n\t\t\t\tstd::vector ::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 ::iterator b = menuOptions.begin();\n\t\t\t\tstd::vector ::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 ::iterator b = menuOptions.begin();\n\tstd::vector ::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":"#include \"unsafearea.hpp\"\n\n#include \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}\ncomment#include \"unsafearea.hpp\"\n\n#include \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":"#include \n\n#include \n#include \n#include \n#include \n#include \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 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);\nmessage: print fromNodeId in toStream().#include \n\n#include \n#include \n#include \n#include \n#include \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 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":"#include \"Configuration.h\"\n#include \"CudaElfFactory.h\"\n#include \"SMPElfFactory.h\"\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \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(&_mode)->required(), \"Mode (smp|cuda)\")\n (\"numwarmups,w\", po::value(&_numberOfWarmUps)->default_value(50), \"Number of warmup rounds\")\n (\"numiter,n\", po::value(&_numberOfIterations)->default_value(100), \"Number of benchmark iterations\")\n (\"input,i\", po::value(&_inputFile), \"Input file\")\n (\"output,o\", po::value(&_outputFile), \"Output file\")\n (\"export_configuration\", po::value(&_exportConfigurationFile), \"Measure cluster and export configuration\")\n (\"import_configuration\", po::value(&_importConfigurationFile), \"Run benchmark with given configuration\")\n (\"skip_benchmark\", \"Skip the benchmark run\")\n (\"left_rows\", po::value(&_leftMatrixRows)->default_value(500), \"Number of left rows to be generated (overridden for benchmark by input file)\")\n (\"common_rows_columns\", po::value(&_commonMatrixRowsColumns)->default_value(500), \"Number of left columns \/ right rows to be generated (overridden for benchmark by input file)\")\n (\"right_columns\", po::value(&_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 generateProblemStatement(string elfCategory, size_t leftRows, size_t commonRowsColumns, size_t rightColumns)\n{\n auto statement = unique_ptr(new ProblemStatement(elfCategory));\n Matrix left(leftRows, commonRowsColumns);\n Matrix right(commonRowsColumns, rightColumns);\n auto distribution = uniform_real_distribution (-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 Configuration::getProblemStatement(bool forceGenerated)\n{\n\n if(!_useFiles || forceGenerated)\n {\n return generateProblemStatement(_category, _leftMatrixRows, _commonMatrixRowsColumns, _rightMatrixColumns);\n }\n return unique_ptr(new ProblemStatement(getElfCategory(), _inputFile, _outputFile));\n}\n\nunique_ptr 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: (\"<configuration now checks the --skip_benchmark flag#include \"Configuration.h\"\n#include \"CudaElfFactory.h\"\n#include \"SMPElfFactory.h\"\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \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(&_mode)->required(), \"Mode (smp|cuda)\")\n (\"numwarmups,w\", po::value(&_numberOfWarmUps)->default_value(50), \"Number of warmup rounds\")\n (\"numiter,n\", po::value(&_numberOfIterations)->default_value(100), \"Number of benchmark iterations\")\n (\"input,i\", po::value(&_inputFile), \"Input file\")\n (\"output,o\", po::value(&_outputFile), \"Output file\")\n (\"export_configuration\", po::value(&_exportConfigurationFile), \"Measure cluster and export configuration\")\n (\"import_configuration\", po::value(&_importConfigurationFile), \"Run benchmark with given configuration\")\n (\"skip_benchmark\", \"Skip the benchmark run\")\n (\"left_rows\", po::value(&_leftMatrixRows)->default_value(500), \"Number of left rows to be generated (overridden for benchmark by input file)\")\n (\"common_rows_columns\", po::value(&_commonMatrixRowsColumns)->default_value(500), \"Number of left columns \/ right rows to be generated (overridden for benchmark by input file)\")\n (\"right_columns\", po::value(&_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 generateProblemStatement(string elfCategory, size_t leftRows, size_t commonRowsColumns, size_t rightColumns)\n{\n auto statement = unique_ptr(new ProblemStatement(elfCategory));\n Matrix left(leftRows, commonRowsColumns);\n Matrix right(commonRowsColumns, rightColumns);\n auto distribution = uniform_real_distribution (-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 Configuration::getProblemStatement(bool forceGenerated)\n{\n\n if(!_useFiles || forceGenerated)\n {\n return generateProblemStatement(_category, _leftMatrixRows, _commonMatrixRowsColumns, _rightMatrixColumns);\n }\n return unique_ptr(new ProblemStatement(getElfCategory(), _inputFile, _outputFile));\n}\n\nunique_ptr 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: (\"<"} {"text":"\/**\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 \n#include \n#include \n#include \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__\nadd hasNext() to JsonIterator. make getPayload() protected.\/**\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 \n#include \n#include \n#include \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":"\/*\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 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(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- removed unused check\/*\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 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(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":"\/\/\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 \n#include \n\n#include \"angle_gl.h\"\n#include \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 ConfigSet::filter(const AttributeMap &attributeMap) const\n{\n std::vector 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}\nDo not use std::set::at in Config.cpp.\/\/\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 \n#include \n\n#include \"angle_gl.h\"\n#include \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 ConfigSet::filter(const AttributeMap &attributeMap) const\n{\n std::vector 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":"\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#include\n#include\n\n#include\"ork\/command_Line.hpp\"\n\n\nnamespace ork {\n\nint invoke_main(const std::vector&args, main_func f) {\n\tstd::vectorargv;\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(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&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_optionsops(options::parse_command_line(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_optionsops(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_optionsops(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_optionsops(options::parse_config_file(config_file, _desc));\n\t\treturn process_commands(ops);\n\t}\n\tCOMMAND_CATCH\n}\n\n}\/\/namespace ork\nAdded a typedef for command parser\/*\nThis file is part of the ORK library.\nFull copyright and license terms can be found in the LICENSE.txt file.\n*\/\n#include\n#include\n\n#include\"ork\/command_Line.hpp\"\n\n\nnamespace ork {\n\nint invoke_main(const std::vector&args, main_func f) {\n\tstd::vectorargv;\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(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&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_optionsops(options::parse_command_line(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;\n#else\nusing command_line_parser = options::basic_command_line_parser;\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_optionsops(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_optionsops(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_optionsops(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":"test: add smoke-crud-onerow.<|endoftext|>"} {"text":"\/* 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 \n#include \n#include \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& TGT0,\n const fapi2::Target& 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 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}\nAdding p9a support.\/* 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 \n#include \n#include \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& TGT0,\n const fapi2::Target& 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 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":"\/*\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}\nfix(library\/expr_lt): fix bug when using hash codes\/*\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":"\/*\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 \n\n#include \n#include \n#include \n#include \n#include \n\/\/ #include \n#include \n#include \n#include \n#include \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& _overlap_cholesky_inverse) {\n \n \/\/ multiply with L-1^t from the right\n \n ub::matrix _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 _eigenvalues;\n ub::matrix _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 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 > result_thread;\n unsigned nthreads = 1;\n #ifdef _OPENMP\n nthreads = omp_get_max_threads();\n #endif\n const ub::vector& qp_energies= _qp_energies;\n \n for(unsigned i=0;i(_size));\n }\n \n #pragma omp parallel for \n for(unsigned thread=0;thread& Mmn_RPA = _Mmn_RPA[ _m_level ];\n#else\n const ub::matrix Mmn_RPA = _Mmn_RPA[ _m_level ];\n#endif\n \/\/ a temporary matrix, that will get filled in empty levels loop\n ub::matrix _temp = ub::matrix(_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 result=ub::zero_matrix(_size);\n for(unsigned thread=0;thread 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& qp_energies= _qp_energies;\n \n std::vector > 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(_size));\n }\n \n #pragma omp parallel for \n for(unsigned thread=0;thread& Mmn_RPA = _Mmn_RPA[ _m_level ];\n#else\n const ub::matrix Mmn_RPA = _Mmn_RPA[ _m_level ];\n#endif\n\n \/\/ a temporary matrix, that will get filled in empty levels loop\n ub::matrix _temp = ub::matrix(_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 result=ub::zero_matrix(_size);\n for(unsigned thread=0;thread 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}};\nbug fixed, now correct\/*\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 \n\n#include \n#include \n#include \n#include \n#include \n\/\/ #include \n#include \n#include \n#include \n#include \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& _overlap_cholesky_inverse) {\n \n \/\/ multiply with L-1^t from the right\n \n ub::matrix _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 _eigenvalues;\n ub::matrix _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 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 > result_thread;\n unsigned nthreads = 1;\n #ifdef _OPENMP\n nthreads = omp_get_max_threads();\n #endif\n const ub::vector& qp_energies= _qp_energies;\n \n for(unsigned i=0;i(_size));\n }\n \n #pragma omp parallel for \n for(unsigned thread=0;thread& Mmn_RPA = _Mmn_RPA[ _m_level ];\n#else\n const ub::matrix Mmn_RPA = _Mmn_RPA[ _m_level ];\n#endif\n \/\/ a temporary matrix, that will get filled in empty levels loop\n ub::matrix _temp = ub::matrix(_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 result=ub::zero_matrix(_size);\n for(unsigned thread=0;thread 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& qp_energies= _qp_energies;\n \n std::vector > 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(_size));\n }\n \n #pragma omp parallel for \n for(unsigned thread=0;thread& Mmn_RPA = _Mmn_RPA[ _m_level ];\n#else\n const ub::matrix Mmn_RPA = _Mmn_RPA[ _m_level ];\n#endif\n\n \/\/ a temporary matrix, that will get filled in empty levels loop\n ub::matrix _temp = ub::matrix(_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 result=ub::zero_matrix(_size);\n for(unsigned thread=0;thread 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":"#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 DisplayMap;\nstd::vector WindowLst;\nstd::vector FloatingSpaceLst;\nstd::vector FloatingAppLst;\nstd::vector 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}\nshould no longer segfault if hotkeys.so becomes unavailable while kwm is running#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 DisplayMap;\nstd::vector WindowLst;\nstd::vector FloatingSpaceLst;\nstd::vector FloatingAppLst;\nstd::vector 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":"\/**************************************************************************\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 \n\n#include \n#include \n#include \n#include \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(m_sequential->animationAt(1))->setEasingCurve(newCurve);\n static_cast(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\"\nQmlDesiger: fixed format for the easing parameters in the easing dialog Reviewed by: Thomas Hartmann\/**************************************************************************\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 \n\n#include \n#include \n#include \n#include \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(m_sequential->animationAt(1))->setEasingCurve(newCurve);\n static_cast(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":"\/\/ 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}\nslightly refactor\/\/ 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":"\/*\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\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(action),\n stop_cond = std::forward(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\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(stop_cond),\n std::forward(action), std::move(p));\n return f;\n}\n\n\/\/ Invoke given action undefinitely. Next invocation starts when previous completes or fails.\ntemplate\nstatic inline\nvoid keep_doing(AsyncAction&& action) {\n while (true) {\n auto f = action();\n if (!f.available()) {\n f.then([action = std::forward(action)] () mutable {\n keep_doing(std::forward(action));\n });\n return;\n }\n }\n}\n\ntemplate\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(action),\n begin = std::move(begin), end = std::move(end)] () mutable {\n return do_for_each(std::move(begin), std::move(end), std::forward(action));\n });\n }\n }\n return make_ready_future<>();\n}\n\n#endif\ncore: make keep_doing() propagate failure\/*\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\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(action),\n stop_cond = std::forward(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\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(stop_cond),\n std::forward(action), std::move(p));\n return f;\n}\n\n\/\/ Invoke given action until it fails.\ntemplate\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(action)] () mutable {\n return keep_doing(std::forward(action));\n });\n }\n\n if (f.failed()) {\n return std::move(f);\n }\n }\n}\n\ntemplate\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(action),\n begin = std::move(begin), end = std::move(end)] () mutable {\n return do_for_each(std::move(begin), std::move(end), std::forward(action));\n });\n }\n }\n return make_ready_future<>();\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\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 \n#include \n#include \n#include \n#include \n\n#include \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>()\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(&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 options =\n flags[\"option\"].as>();\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 lock(mutex_);\n project_id_ =\n config[\"ProjectId\"].as(project_id_);\n credentials_file_ =\n config[\"CredentialsFile\"].as(credentials_file_);\n metadata_api_num_threads_ =\n config[\"MetadataApiNumThreads\"].as(metadata_api_num_threads_);\n metadata_api_port_ =\n config[\"MetadataApiPort\"].as(metadata_api_port_);\n metadata_api_resource_type_separator_ =\n config[\"MetadataApiResourceTypeSeparator\"].as(\n metadata_api_resource_type_separator_);\n metadata_reporter_interval_seconds_ =\n config[\"MetadataReporterIntervalSeconds\"].as(\n metadata_reporter_interval_seconds_);\n metadata_reporter_purge_deleted_ =\n config[\"MetadataReporterPurgeDeleted\"].as(\n metadata_reporter_purge_deleted_);\n metadata_reporter_user_agent_ =\n config[\"MetadataReporterUserAgent\"].as(\n metadata_reporter_user_agent_);\n metadata_ingestion_endpoint_format_ =\n config[\"MetadataIngestionEndpointFormat\"].as(\n metadata_ingestion_endpoint_format_);\n metadata_ingestion_request_size_limit_bytes_ =\n config[\"MetadataIngestionRequestSizeLimitBytes\"].as(\n metadata_ingestion_request_size_limit_bytes_);\n metadata_ingestion_request_size_limit_count_ =\n config[\"MetadataIngestionRequestSizeLimitCount\"].as(\n metadata_ingestion_request_size_limit_count_);\n metadata_ingestion_raw_content_version_ =\n config[\"MetadataIngestionRawContentVersion\"].as(\n metadata_ingestion_raw_content_version_);\n instance_updater_interval_seconds_ =\n config[\"InstanceUpdaterIntervalSeconds\"].as(\n instance_updater_interval_seconds_);\n instance_resource_type_ =\n config[\"InstanceResourceType\"].as(instance_resource_type_);\n docker_updater_interval_seconds_ =\n config[\"DockerUpdaterIntervalSeconds\"].as(\n docker_updater_interval_seconds_);\n docker_endpoint_host_ =\n config[\"DockerEndpointHost\"].as(docker_endpoint_host_);\n docker_api_version_ =\n config[\"DockerApiVersion\"].as(docker_api_version_);\n docker_container_filter_ =\n config[\"DockerContainerFilter\"].as(\n docker_container_filter_);\n kubernetes_updater_interval_seconds_ =\n config[\"KubernetesUpdaterIntervalSeconds\"].as(\n kubernetes_updater_interval_seconds_);\n kubernetes_endpoint_host_ =\n config[\"KubernetesEndpointHost\"].as(\n kubernetes_endpoint_host_);\n kubernetes_pod_label_selector_ =\n config[\"KubernetesPodLabelSelector\"].as(\n kubernetes_pod_label_selector_);\n kubernetes_cluster_name_ =\n config[\"KubernetesClusterName\"].as(\n kubernetes_cluster_name_);\n kubernetes_cluster_location_ =\n config[\"KubernetesClusterLocation\"].as(\n kubernetes_cluster_location_);\n kubernetes_node_name_ =\n config[\"KubernetesNodeName\"].as(kubernetes_node_name_);\n kubernetes_use_watch_ =\n config[\"KubernetesUseWatch\"].as(kubernetes_use_watch_);\n kubernetes_cluster_level_metadata_ =\n config[\"KubernetesClusterLevelMetadata\"].as(\n kubernetes_cluster_level_metadata_);\n kubernetes_service_metadata_ =\n config[\"KubernetesServiceMetadata\"].as(\n kubernetes_service_metadata_);\n instance_id_ =\n config[\"InstanceId\"].as(instance_id_);\n instance_zone_ =\n config[\"InstanceZone\"].as(instance_zone_);\n health_check_file_ =\n config[\"HealthCheckFile\"].as(health_check_file_);\n}\n\n} \/\/ google\n\n#undef STRINGIFY\n#undef STRINGIFY_H\nIn configuration.cc, change LOG(DEBUG) to std::cout. (#144)\/*\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 \n#include \n#include \n#include \n#include \n\n#include \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>()\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(&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 options =\n flags[\"option\"].as>();\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 lock(mutex_);\n project_id_ =\n config[\"ProjectId\"].as(project_id_);\n credentials_file_ =\n config[\"CredentialsFile\"].as(credentials_file_);\n metadata_api_num_threads_ =\n config[\"MetadataApiNumThreads\"].as(metadata_api_num_threads_);\n metadata_api_port_ =\n config[\"MetadataApiPort\"].as(metadata_api_port_);\n metadata_api_resource_type_separator_ =\n config[\"MetadataApiResourceTypeSeparator\"].as(\n metadata_api_resource_type_separator_);\n metadata_reporter_interval_seconds_ =\n config[\"MetadataReporterIntervalSeconds\"].as(\n metadata_reporter_interval_seconds_);\n metadata_reporter_purge_deleted_ =\n config[\"MetadataReporterPurgeDeleted\"].as(\n metadata_reporter_purge_deleted_);\n metadata_reporter_user_agent_ =\n config[\"MetadataReporterUserAgent\"].as(\n metadata_reporter_user_agent_);\n metadata_ingestion_endpoint_format_ =\n config[\"MetadataIngestionEndpointFormat\"].as(\n metadata_ingestion_endpoint_format_);\n metadata_ingestion_request_size_limit_bytes_ =\n config[\"MetadataIngestionRequestSizeLimitBytes\"].as(\n metadata_ingestion_request_size_limit_bytes_);\n metadata_ingestion_request_size_limit_count_ =\n config[\"MetadataIngestionRequestSizeLimitCount\"].as(\n metadata_ingestion_request_size_limit_count_);\n metadata_ingestion_raw_content_version_ =\n config[\"MetadataIngestionRawContentVersion\"].as(\n metadata_ingestion_raw_content_version_);\n instance_updater_interval_seconds_ =\n config[\"InstanceUpdaterIntervalSeconds\"].as(\n instance_updater_interval_seconds_);\n instance_resource_type_ =\n config[\"InstanceResourceType\"].as(instance_resource_type_);\n docker_updater_interval_seconds_ =\n config[\"DockerUpdaterIntervalSeconds\"].as(\n docker_updater_interval_seconds_);\n docker_endpoint_host_ =\n config[\"DockerEndpointHost\"].as(docker_endpoint_host_);\n docker_api_version_ =\n config[\"DockerApiVersion\"].as(docker_api_version_);\n docker_container_filter_ =\n config[\"DockerContainerFilter\"].as(\n docker_container_filter_);\n kubernetes_updater_interval_seconds_ =\n config[\"KubernetesUpdaterIntervalSeconds\"].as(\n kubernetes_updater_interval_seconds_);\n kubernetes_endpoint_host_ =\n config[\"KubernetesEndpointHost\"].as(\n kubernetes_endpoint_host_);\n kubernetes_pod_label_selector_ =\n config[\"KubernetesPodLabelSelector\"].as(\n kubernetes_pod_label_selector_);\n kubernetes_cluster_name_ =\n config[\"KubernetesClusterName\"].as(\n kubernetes_cluster_name_);\n kubernetes_cluster_location_ =\n config[\"KubernetesClusterLocation\"].as(\n kubernetes_cluster_location_);\n kubernetes_node_name_ =\n config[\"KubernetesNodeName\"].as(kubernetes_node_name_);\n kubernetes_use_watch_ =\n config[\"KubernetesUseWatch\"].as(kubernetes_use_watch_);\n kubernetes_cluster_level_metadata_ =\n config[\"KubernetesClusterLevelMetadata\"].as(\n kubernetes_cluster_level_metadata_);\n kubernetes_service_metadata_ =\n config[\"KubernetesServiceMetadata\"].as(\n kubernetes_service_metadata_);\n instance_id_ =\n config[\"InstanceId\"].as(instance_id_);\n instance_zone_ =\n config[\"InstanceZone\"].as(instance_zone_);\n health_check_file_ =\n config[\"HealthCheckFile\"].as(health_check_file_);\n}\n\n} \/\/ google\n\n#undef STRINGIFY\n#undef STRINGIFY_H\n<|endoftext|>"} {"text":"\/*\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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\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\nLexerBase::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\nLexerBase::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 \nToken LexerBase::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 \nToken LexerBase::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(startIndex);\n lineToken.size = stopIndex - static_cast(startIndex);\n return lineToken;\n}\n\ntemplate\nstd::string LexerBase::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(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(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\nvoid LexerBase::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 \nvoid LexerBase::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\nbool LexerBase::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;\n\n\n} \/\/ namespace parser_base\n} \/\/ namespace ydsh\n\n#endif \/\/YDSH_LEXER_BASE_HPP\nLexerBase is move assignable\/*\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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\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\nLexerBase::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\nLexerBase::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 \nToken LexerBase::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 \nToken LexerBase::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(startIndex);\n lineToken.size = stopIndex - static_cast(startIndex);\n return lineToken;\n}\n\ntemplate\nstd::string LexerBase::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(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(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\nvoid LexerBase::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 \nvoid LexerBase::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\nbool LexerBase::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;\n\n\n} \/\/ namespace parser_base\n} \/\/ namespace ydsh\n\n#endif \/\/YDSH_LEXER_BASE_HPP\n<|endoftext|>"} {"text":"#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}\nRemoved unneeded parenthesis#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":"#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 \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(glGetString(GL_VERSION)));\n\t\t\tstd::printf(\"\\nGL_SHADING_LANGUAGE_VERSION: %s\\n\\n\", reinterpret_cast(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.\nBUg fix! Crashes on nvidia cards.#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 \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(glGetString(GL_VERSION)));\n\t\t\tstd::printf(\"\\nGL_SHADING_LANGUAGE_VERSION: %s\\n\\n\", reinterpret_cast(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":"\/\/ 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef WIN32\n#include \n#else\n#include \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 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\nFirst (hacky) draft at sorting out JS module scope problem\/\/ 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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#ifdef WIN32\n#include \n#else\n#include \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 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":"\/\/ 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 \n#include \n#include \n#include \n\n#ifdef WIN32\n#include \n#else\n#define SHLIBPREFIX \"lib\"\n#include \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(object());\n require* r = static_cast(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(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 \n\nstring transcode_js_file(fs::path filename) {\n io::file &f = create_native_object(\n object(),\n filename.string().c_str(),\n value(\"r\")\n );\n\n \/\/ buffer blob\n byte_array &blob = create_native_object(\n object(),\n static_cast(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 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\ncore\/require: Don't replace extension, add to it.\/\/ 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 \n#include \n#include \n#include \n\n#ifdef WIN32\n#include \n#else\n#define SHLIBPREFIX \"lib\"\n#include \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(object());\n require* r = static_cast(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(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 \n\nstring transcode_js_file(fs::path filename) {\n io::file &f = create_native_object(\n object(),\n filename.string().c_str(),\n value(\"r\")\n );\n\n \/\/ buffer blob\n byte_array &blob = create_native_object(\n object(),\n static_cast(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 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":"\/\/=======================================================================\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 \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 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& 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> 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 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 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& lhs, const mtac::Domain& 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& lhs, const mtac::Domain& rhs){\n return !(lhs == rhs);\n}\nMake sure to avoid loops\/\/=======================================================================\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 \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 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& tj, mtac::Operator op, mtac::basic_block_p& block, std::unordered_set& 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> 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 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 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 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& lhs, const mtac::Domain& 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& lhs, const mtac::Domain& rhs){\n return !(lhs == rhs);\n}\n<|endoftext|>"} {"text":"#include \"common.hpp\"\n#include \n#include \n\n#include \n#include \n#include \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().get_id();\n case SOCK_DGRAM:\n return FD_map::_open().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\"\nmusl: Only support AF_INET (ip4) sockets#include \"common.hpp\"\n#include \n#include \n\n#include \n#include \n#include \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().get_id();\n case SOCK_DGRAM:\n return FD_map::_open().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":"#include \"hecl\/HMDLMeta.hpp\"\n\n#include \"hecl\/Runtime.hpp\"\n\n#include \n#include \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\nHMDL_RT: Make use of std::make_unique#include \"hecl\/HMDLMeta.hpp\"\n\n#include \"hecl\/Runtime.hpp\"\n\n#include \n#include \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(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":"#include \n#include \n#include \n#include \n#include \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();\n\n \/\/ Add the methods.\n flusspferd::create(\n \"dump\", &StringSet::dump, _container = proto);\n flusspferd::create(\n \"add\", &StringSet::add, _container = proto);\n flusspferd::create(\n \"delete\", &StringSet::delete_, _container = proto);\n flusspferd::create(\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 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());\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(\"print\", &print, _container = flusspferd::global());\n\n flusspferd::load_class();\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}\nhelp\/examples: make example benefit from create_on#include \n#include \n#include \n#include \n#include \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();\n\n \/\/ Add the methods.\n flusspferd::create_on(proto)\n .create(\"dump\", &StringSet::dump)\n .create(\"add\", &StringSet::add)\n .create(\"delete\", &StringSet::delete_)\n .create(\"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 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());\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(\"print\", &print, _container = flusspferd::global());\n\n flusspferd::load_class();\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":"\/\/===--- 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}\nHandle the 'n' constraint\/\/===--- 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":"\/*************************************************************************\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 \n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n#ifndef _FORMAT_HXX\n#include \n#endif\n#ifndef _SWTYPES_HXX\n#include \/\/ 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 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\nINTEGRATION: CWS swwarnings (1.9.16); FILE MERGED 2007\/02\/27 13:06:33 tl 1.9.16.1: #i69287# warning-free code\/*************************************************************************\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 \n#endif\n\n#ifndef INCLUDED_SWDLLAPI_H\n#include \"swdllapi.h\"\n#endif\n#ifndef _FORMAT_HXX\n#include \n#endif\n#ifndef _SWTYPES_HXX\n#include \/\/ 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 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":"Ajout de la préparation du kernel (buffer des infos).<|endoftext|>"} {"text":"\/*\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 .\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\nvoid clique::numeric::SetSolveMode( DistSymmFact& 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& leafSN = distL.supernodes[0];\n if( mode == FEW_RHS )\n {\n leafSN.front1d.LocalMatrix().View( leafSN.front2d.LocalMatrix() );\n for( int k=1; k& 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& 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 \/\/ 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& localL,\n numeric::DistSymmFact& 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& topLocalSN = localL.supernodes.back();\n DistSymmFactSupernode& 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::const_iterator it;\n for( unsigned k=1; k& childNumSN = distL.supernodes[k-1];\n DistSymmFactSupernode& 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 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 sendBuffer( sendPortionSize*commSize );\n\n const std::vector& 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 sendOffsets( commSize );\n for( int proc=0; proc 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& recvIndices = \n symbSN.childFactRecvIndices[proc];\n for( int k=0; k& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n symbolic::DistSymmFact& S,\n const numeric::LocalSymmFact& localL,\n numeric::DistSymmFact& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n symbolic::DistSymmFact& S,\n const numeric::LocalSymmFact& localL,\n numeric::DistSymmFact& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact >& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n symbolic::DistSymmFact& S,\n const numeric::LocalSymmFact >& localL,\n numeric::DistSymmFact >& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact >& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n symbolic::DistSymmFact& S,\n const numeric::LocalSymmFact >& localL,\n numeric::DistSymmFact >& distL );\nFixed an indexing mistake in DistLDL.\/*\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 .\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\nvoid clique::numeric::SetSolveMode( DistSymmFact& 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& leafSN = distL.supernodes[0];\n if( mode == FEW_RHS )\n {\n leafSN.front1d.LocalMatrix().View( leafSN.front2d.LocalMatrix() );\n for( int k=1; k& 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& 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 \/\/ 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& localL,\n numeric::DistSymmFact& 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& topLocalSN = localL.supernodes.back();\n DistSymmFactSupernode& 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::const_iterator it;\n for( unsigned k=1; k& childNumSN = distL.supernodes[k-1];\n DistSymmFactSupernode& 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 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 sendBuffer( sendPortionSize*commSize );\n\n const std::vector& 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 sendOffsets( commSize );\n for( int proc=0; proc 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& recvIndices = \n symbSN.childFactRecvIndices[proc];\n const int numRecvIndexPairs = recvIndices.size()\/2;\n for( int k=0; k& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n symbolic::DistSymmFact& S,\n const numeric::LocalSymmFact& localL,\n numeric::DistSymmFact& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n symbolic::DistSymmFact& S,\n const numeric::LocalSymmFact& localL,\n numeric::DistSymmFact& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact >& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n symbolic::DistSymmFact& S,\n const numeric::LocalSymmFact >& localL,\n numeric::DistSymmFact >& distL );\n\ntemplate void clique::numeric::SetSolveMode\n( DistSymmFact >& distL, SolveMode mode );\ntemplate void clique::numeric::DistLDL\n( Orientation orientation,\n symbolic::DistSymmFact& S,\n const numeric::LocalSymmFact >& localL,\n numeric::DistSymmFact >& distL );\n<|endoftext|>"} {"text":"\/*************************************************************************\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 \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\nINTEGRATION: 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\/*************************************************************************\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 \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":"#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \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 parent = _parent;\r\n ref_ptr ps = new ParticleSystem();\r\n ps->getDefaultParticleTemplate().setShape(Particle::POINT);\r\n \r\n ref_ptr 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 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 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 attribute = new Point(10.0f);\r\n ss->setAttribute(attribute);\r\n ref_ptr 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 rrc = new RandomRateCounter();\r\n rrc->setRateRange( 50, 500 ); \/\/Anzahl der Partikel\/Sekunde\r\n \r\n \/\/makeshooter\r\n ref_ptr 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 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 program = new ModularProgram();\r\n \/\/ program->setParticleSystem( ps.get() );\r\n\r\n \r\n \/\/Rendering stuff2\r\n ref_ptr 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 rotator = new ph::Rotator(-1.7, 1.81, 30);\r\n rotator->setTexture(0, \"..\/resources\/rotator_tx.png\");\r\n \r\n ref_ptr fins1a = new ph::Fins(0,0.4);\r\n fins1a->setTexture(0, \"..\/resources\/fin.png\");\r\n \r\n osg::ref_ptr 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 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 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 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 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 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 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 lm = new LightModel;\r\n lm->setTwoSided(true);\r\n fins1->getOrCreateStateSet()->setAttributeAndModes(lm.get());\r\n\r\n ref_ptr sphere = new ph::Sphere(0.1, 200);\r\n ref_ptr 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 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 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 ps = createParticleSystem(mtx.get());\r\n ref_ptr updater = new ParticleSystemUpdater();\r\n updater->addParticleSystem(ps);\r\n\r\n ref_ptr 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 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\nMissile - nun das aktuelle committed#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \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 parent = _parent;\r\n ref_ptr ps = new ParticleSystem();\r\n ps->getDefaultParticleTemplate().setShape(Particle::POINT);\r\n \r\n ref_ptr 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 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 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 attribute = new Point(10.0f);\r\n ss->setAttribute(attribute);\r\n ref_ptr 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 rrc = new RandomRateCounter();\r\n rrc->setRateRange( 50, 500 ); \/\/Anzahl der Partikel\/Sekunde\r\n \r\n \/\/makeshooter\r\n ref_ptr 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 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 = 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 rotator = new ph::Rotator(-1.7, 1.81, 30);\r\n rotator->setTexture(0, \"..\/resources\/rotator_tx.png\");\r\n \r\n ref_ptr fins1a = new ph::Fins(0,0.4);\r\n fins1a->setTexture(0, \"..\/resources\/fin.png\");\r\n \r\n osg::ref_ptr 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 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 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 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 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 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 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 lm = new LightModel;\r\n lm->setTwoSided(true);\r\n fins1->getOrCreateStateSet()->setAttributeAndModes(lm.get());\r\n\r\n ref_ptr sphere = new ph::Sphere(0.1, 200);\r\n ref_ptr 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 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 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 ps = createParticleSystem(mtx.get());\r\n ref_ptr updater = new ParticleSystemUpdater();\r\n updater->addParticleSystem(ps);\r\n\r\n ref_ptr 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 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":"\/\/ Time: O(max(r, c) * wlogw)\n\/\/ Space: O(w^2)\n\nclass Solution {\npublic:\n string findShortestWay(vector>& maze, vector& ball, vector& hole) {\n static const unordered_map> dirs = {{\"u\", {-1, 0}}, {\"r\", {0, 1}},\n {\"l\", {0, -1}}, {\"d\", {1, 0}}};\n queue heap;\n unordered_set visited;\n heap.emplace(0, make_pair(\"\", ball));\n\n while (!heap.empty()) {\n int dist = 0;\n string path;\n vector 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 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>>;\n\n node findNeighbor(const vector>& maze, const vector& hole,\n const vector& node, const pair>& kvp) {\n string dir;\n vector vec;\n tie(dir, vec) = kvp;\n vector 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>& maze, const vector& node) {\n return node[0] * maze[0].size() + node[1];\n }\n\n template \n constexpr T &lvalue(T &&v) {\n return v;\n }\n};\nUpdate the-maze-iii.cpp\/\/ Time: O(max(r, c) * wlogw)\n\/\/ Space: O(w^2)\n\nclass Solution {\npublic:\n string findShortestWay(vector>& maze, vector& ball, vector& hole) {\n static const unordered_map> dirs = {{\"u\", {-1, 0}}, {\"r\", {0, 1}},\n {\"l\", {0, -1}}, {\"d\", {1, 0}}};\n priority_queue, greater> heap;\n unordered_set visited;\n heap.emplace(0, make_pair(\"\", ball));\n\n while (!heap.empty()) {\n int dist = 0;\n string path;\n vector 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 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>>;\n\n node findNeighbor(const vector>& maze, const vector& hole,\n const vector& node, const pair>& kvp) {\n string dir;\n vector vec;\n tie(dir, vec) = kvp;\n vector 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>& maze, const vector& node) {\n return node[0] * maze[0].size() + node[1];\n }\n\n template \n constexpr T &lvalue(T &&v) {\n return v;\n }\n};\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nusing namespace std;\n\nclass Solution {\n \npublic:\n vector > threeSum(vector &num) {\n \n vector>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 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 v(a, a+5);\n cout << s.threeSum(v).size();\n \n return 0;\n}15. 3Sumclass Solution {\n \npublic:\n vector > threeSum(vector &num) {\n vector> 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 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":"#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\n\ntemplate T inf;\ntemplate<> constexpr int inf = 1e9;\ntemplate<> constexpr ll inf = 1e18;\ntemplate<> constexpr ld inf = 1e30;\nAdd include#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nusing ll = long long;\nusing ld = long double;\n\ntemplate T inf;\ntemplate<> constexpr int inf = 1e9;\ntemplate<> constexpr ll inf = 1e18;\ntemplate<> constexpr ld inf = 1e30;\n<|endoftext|>"} {"text":"#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}\nfix bug#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":"#include \n#include \n#include \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 \" << endl;\n}\nУбрал закомментированный код.#include \n#include \n#include \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 \" << endl;\n}\n<|endoftext|>"} {"text":"\/* 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 \n Luís Pereira \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \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 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 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)\nTranslator: Prefer XDG_DATA_DIRS over compiled in path\/* 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 \n Luís Pereira \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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \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 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 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":"#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 >::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::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 >::iterator group = grouped_files.begin(); group != grouped_files.end(); ++group) {\n\t\tfor (vector::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 \" ()\" before extension\n\t * until we find an available filename or 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 files = database->loadMetafiles(\"\");\n\tstruct stat file_info;\n\tfor (vector::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 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 files = database->loadMetafiles(filename_without_extension);\n\tunsigned long file_quality = file->bitrate * file->channels * file->samplerate;\n\tfor (vector::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 >::iterator gf = grouped_files.begin(); gf != grouped_files.end() && !stop; ++gf) {\n\t\t\tfor (vector::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}\nsetting 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.#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 >::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::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 >::iterator group = grouped_files.begin(); group != grouped_files.end(); ++group) {\n\t\tfor (vector::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 \" ()\" before extension\n\t * until we find an available filename or 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 files = database->loadMetafiles(\"\");\n\tstruct stat file_info;\n\tfor (vector::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 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 files = database->loadMetafiles(filename_without_extension);\n\tunsigned long file_quality = file->bitrate * file->channels * file->samplerate;\n\tfor (vector::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 >::iterator gf = grouped_files.begin(); gf != grouped_files.end() && !stop; ++gf) {\n\t\t\tfor (vector::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":"#include \"lexer.hpp\"\n\n#include \n#include \n#include \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 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\nAdd COMMENT and STRING#include \"lexer.hpp\"\n\n#include \n#include \n#include \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 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":"\/*\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 \n\/\/#include \n#include \n\n\n\n\/*\nanalyze an input file and returns its contents as a list of tokens\n*\/\nstd::vector tuc::lex_analyze(const std::string& filePath) {\n auto inputFile = std::ifstream{filePath};\n std::stringbuf sb;\n inputFile.get(sb, static_cast(-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 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}\nClean up code.\/*\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 \n\/\/#include \n#include \n\n\n\n\/*\nanalyze an input file and returns its contents as a list of tokens\n*\/\nstd::vector tuc::lex_analyze(const std::string& filePath) {\n auto inputFile = std::ifstream{filePath};\n std::stringbuf sb;\n inputFile.get(sb, static_cast(-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 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":"\/\/ 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 \n#include \n#include \n#include \n#include \n#include \n\nnamespace Nz\n{\n\tinline VirtualDirectory::VirtualDirectory(std::weak_ptr 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 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\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 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 physicalPathBase;\n\t\tstd::vector 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(&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(&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\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;\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)\n\t\t\t\t{\n\t\t\t\t\treturn CallbackReturn(callback, static_cast(entry.data), SafeCast(entry.size));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v)\n\t\t\t\t{\n\t\t\t\t\treturn CallbackReturn(callback, static_cast(entry.data.data()), SafeCast(entry.data.size()));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v)\n\t\t\t\t{\n\t\t\t\t\tstd::optional> 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(source->data()), SafeCast(source->size()));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v || std::is_same_v)\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(), \"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 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 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 file) -> FileContentEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr 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 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 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 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& 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(&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(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\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(entryPtr->entry);\n\t}\n\n\ttemplate\n\tbool VirtualDirectory::CallbackReturn(F&& callback, Args&& ...args)\n\t{\n\t\tusing Ret = decltype(callback(std::forward(args)...));\n\t\tif constexpr (std::is_void_v)\n\t\t{\n\t\t\tcallback(std::forward(args)...);\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstatic_assert(std::is_same_v, \"callback must either return a boolean or nothing\");\n\t\t\treturn callback(std::forward(args)...);\n\t\t}\n\t}\n\n\ttemplate\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 \nCore\/VirtualDirectory: Prevent storing . and .. entries\/\/ 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 \n#include \n#include \n#include \n#include \n#include \n\nnamespace Nz\n{\n\tinline VirtualDirectory::VirtualDirectory(std::weak_ptr 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 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\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 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 physicalPathBase;\n\t\tstd::vector 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(&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(&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\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;\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)\n\t\t\t\t{\n\t\t\t\t\treturn CallbackReturn(callback, static_cast(entry.data), SafeCast(entry.size));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v)\n\t\t\t\t{\n\t\t\t\t\treturn CallbackReturn(callback, static_cast(entry.data.data()), SafeCast(entry.data.size()));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v)\n\t\t\t\t{\n\t\t\t\t\tstd::optional> 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(source->data()), SafeCast(source->size()));\n\t\t\t\t}\n\t\t\t\telse if constexpr (std::is_same_v || std::is_same_v)\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(), \"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 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 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 file) -> FileContentEntry&\n\t{\n\t\tassert(!path.empty());\n\n\t\tstd::shared_ptr 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 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 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 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& 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(&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(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\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(entryPtr->entry);\n\t}\n\n\ttemplate\n\tbool VirtualDirectory::CallbackReturn(F&& callback, Args&& ...args)\n\t{\n\t\tusing Ret = decltype(callback(std::forward(args)...));\n\t\tif constexpr (std::is_void_v)\n\t\t{\n\t\t\tcallback(std::forward(args)...);\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstatic_assert(std::is_same_v, \"callback must either return a boolean or nothing\");\n\t\t\treturn callback(std::forward(args)...);\n\t\t}\n\t}\n\n\ttemplate\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 \n<|endoftext|>"} {"text":"#include \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}\nA little less output#include \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":"\/\/\/ 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 \n\n#include \"soa\/table.hpp\"\n#include \"aosoa\/table_iterator.hpp\"\n\nnamespace aosoa {\n\n template\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 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\n inline void indexed_for_each_range(const table_iterator& begin,\n\t\t\t\t\t\t\t\t\t const table_iterator& 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; ifixed typo\/\/\/ 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 \n\n#include \"soa\/table.hpp\"\n#include \"aosoa\/table_iterator.hpp\"\n\nnamespace aosoa {\n\n template\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 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\n inline void indexed_for_each_range(const table_iterator& begin,\n\t\t\t\t\t\t\t\t\t const table_iterator& 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"} {"text":"\/*\n * Copyright (C) 2014 Pelagicore AB\n * All rights reserved.\n *\/\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \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 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 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\ndbusgateway_unittest.cpp: fix failing test\/*\n * Copyright (C) 2014 Pelagicore AB\n * All rights reserved.\n *\/\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\n#include \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 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 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":"\/\/ ======================================================================== \/\/\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 &world,\n const xml::Node &xmlNode)\n {\n using SVFF = StructuredVolumeFromFile;\n auto volume = createNode(\"volume\",\n \"StructuredVolumeFromFile\")->nodeAs();\n\n vec3i dimensions(-1);\n vec3f gridSpacing = volume->child(\"gridSpacing\").valueAs();\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 &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();\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 &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 &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\nadd ability to specify slices in .osp files\/\/ ======================================================================== \/\/\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 &world,\n const xml::Node &xmlNode)\n {\n using SVFF = StructuredVolumeFromFile;\n auto volume = createNode(\"volume\",\n \"StructuredVolumeFromFile\")->nodeAs();\n\n vec3i dimensions(-1);\n vec3f gridSpacing = volume->child(\"gridSpacing\").valueAs();\n std::string volumeFileName = \"\";\n std::string voxelType = \"\";\n\n containers::AlignedVector 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();\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 &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();\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 &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 &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":"#include \"curltools.h\"\n\n#include \n#include \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 *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(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 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}\nThread-safety fix in curl.#include \"curltools.h\"\n\n#include \n#include \n#include \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 *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(NULL));\n#endif\n\n CURL *curl;\n CURLcode res;\n\n {\n boost::lock_guard lg(curl_global_init_lock);\n curl_global_init(CURL_GLOBAL_DEFAULT);\n }\n\n curl = curl_easy_init();\n std::deque 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":"\/***********************************************************************\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 \n#include \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 \n#include \n#include \n\n#ifdef __APPLE__\n# include \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\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(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 );\nBetter default CEGUI_SAMPLE_DATAPATH for AutoQA\/***********************************************************************\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 \n#include \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 \n#include \n#include \n\n#ifdef __APPLE__\n# include \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\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(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":"\/\/ 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 &file, const std::shared_ptr &block,\n const std::string &loc)\n : EntityWithSourcesFS(file, block, loc)\n{\n createSubFolders(file);\n}\n\n\nGroupFS::GroupFS(const std::shared_ptr &file, const std::shared_ptr &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 &file, const std::shared_ptr &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 &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(block()->getDataArray(name_or_id));\n data_array_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr GroupFS::getDataArray(const std::string &name_or_id) const {\n std::shared_ptr 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 path = data_array_group.findByNameOrAttribute(\"name\", name_or_id);\n if (path) {\n return std::make_shared(file(), block(), path->string());\n }\n }\n return da;\n}\n\n\nstd::shared_ptr 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(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 &data_arrays) {\n \/\/ extract vectors of names from vectors of new & old references\n std::vector names_new(data_arrays.size());\n transform(data_arrays.begin(), data_arrays.end(), names_new.begin(), util::toName);\n\n size_t count = nix::check::fits_in_size_t(dataArrayCount(), \"dataArrayCount failed! count > than size_t!\");\n std::vector refs_old(count);\n for (size_t i = 0; i < refs_old.size(); i++){\n refs_old[i] = getDataArray(i);\n }\n std::vector names_old(refs_old.size());\n std::transform(refs_old.begin(), refs_old.end(), names_old.begin(), util::toName);\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 names_add;\n std::vector 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(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(block()->getTag(name_or_id));\n tag_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr GroupFS::getTag(const std::string &name_or_id) const {\n std::shared_ptr 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 path = tag_group.findByNameOrAttribute(\"name\", name_or_id);\n if (path) {\n return std::make_shared(file(), block(), path->string());\n }\n }\n return tag;\n}\n\n\nstd::shared_ptr 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(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 &tags) {\n \/\/ extract vectors of names from vectors of new & old references\n std::vector names_new(tags.size());\n transform(tags.begin(), tags.end(), names_new.begin(), util::toName);\n\n size_t count = nix::check::fits_in_size_t(tagCount(), \"tagCount() failed! count > than size_t!\");\n std::vector refs_old(count);\n for (size_t i = 0; i < refs_old.size(); i++){\n refs_old[i] = getTag(i);\n }\n std::vector names_old(refs_old.size());\n std::transform(refs_old.begin(), refs_old.end(), names_old.begin(), util::toName);\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 names_add;\n std::vector 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(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(block()->getMultiTag(name_or_id));\n multi_tag_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr GroupFS::getMultiTag(const std::string &name_or_id) const {\n std::shared_ptr 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 path = multi_tag_group.findByNameOrAttribute(\"name\", name_or_id);\n if (path) {\n return std::make_shared(file(), block(), path->string());\n }\n }\n return mtag;\n}\n\n\nstd::shared_ptr 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(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 &multi_tags) {\n \/\/ extract vectors of names from vectors of new & old references\n std::vector names_new(multi_tags.size());\n transform(multi_tags.begin(), multi_tags.end(), names_new.begin(), util::toName);\n\n size_t count = nix::check::fits_in_size_t(multiTagCount(), \"multiTagCount() failed! count > than size_t!\");\n std::vector refs_old(count);\n for (size_t i = 0; i < refs_old.size(); i++){\n refs_old[i] = getMultiTag(i);\n }\n std::vector names_old(refs_old.size());\n std::transform(refs_old.begin(), refs_old.end(), names_old.begin(), util::toName);\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 names_add;\n std::vector 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(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[GroupFS] change vector setter to check for name and id\/\/ 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 &file, const std::shared_ptr &block,\n const std::string &loc)\n : EntityWithSourcesFS(file, block, loc)\n{\n createSubFolders(file);\n}\n\n\nGroupFS::GroupFS(const std::shared_ptr &file, const std::shared_ptr &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 &file, const std::shared_ptr &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 &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(block()->getDataArray(name_or_id));\n data_array_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr GroupFS::getDataArray(const std::string &name_or_id) const {\n std::shared_ptr 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 path = data_array_group.findByNameOrAttribute(\"name\", name_or_id);\n if (path) {\n return std::make_shared(file(), block(), path->string());\n }\n }\n return da;\n}\n\n\nstd::shared_ptr 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(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 &data_arrays) {\n auto cmp = [](const DataArray &a, const DataArray& b) { return a.name() < b.name(); };\n std::vector 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 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 add;\n std::vector 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(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(block()->getTag(name_or_id));\n tag_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr GroupFS::getTag(const std::string &name_or_id) const {\n std::shared_ptr 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 path = tag_group.findByNameOrAttribute(\"name\", name_or_id);\n if (path) {\n return std::make_shared(file(), block(), path->string());\n }\n }\n return tag;\n}\n\n\nstd::shared_ptr 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(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 &tags) {\n auto cmp = [](const Tag &a, const Tag& b) { return a.name() < b.name(); };\n \n std::vector new_tags(tags); \n size_t tag_count = nix::check::fits_in_size_t(tagCount(), \"tagCount() failed; count > size_t.\");\n std::vector 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 add;\n std::vector 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(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(block()->getMultiTag(name_or_id));\n multi_tag_group.createDirectoryLink(target->location(), target->id());\n}\n\n\nstd::shared_ptr GroupFS::getMultiTag(const std::string &name_or_id) const {\n std::shared_ptr 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 path = multi_tag_group.findByNameOrAttribute(\"name\", name_or_id);\n if (path) {\n return std::make_shared(file(), block(), path->string());\n }\n }\n return mtag;\n}\n\n\nstd::shared_ptr 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(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 &multi_tags) {\n auto cmp = [](const MultiTag &a, const MultiTag& b) { return a.name() < b.name(); };\n std::vector new_tags(multi_tags); \n size_t tag_count = nix::check::fits_in_size_t(multiTagCount(), \"multiTagCount() failed; count > size_t.\");\n std::vector 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 add;\n std::vector 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(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":"Hotfix to prevent segfault while importing backups<|endoftext|>"} {"text":"#include \"painter\/painter.hpp\"\n#include \n#include \n#include \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\nAdd special case for border to print in corners#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 \n\n#include \n#include \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":"\/\/\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 \n#include \n#include \n#include \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 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(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 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 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 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(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 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\ncpplint errors\/\/\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 \n#include \n#include \n#include \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 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(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 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 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 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(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 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":"\/****************************************************************************\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 \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::children() const\n{\n QList 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 QmlItemNode::resources() const\n{\n QList 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 QmlItemNode::defaultPropertyChildren() const\n{\n QList 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 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 QmlModelStateGroup::allStates() const\n{\n QList 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 toModelNodeList(const QList &qmlItemNodeList)\n{\n QList modelNodeList;\n\n foreach (const QmlItemNode &qmlItemNode, qmlItemNodeList)\n modelNodeList.append(qmlItemNode.modelNode());\n\n return modelNodeList;\n}\n\nQList toQmlItemNodeList(const QList &modelNodeList)\n{\n QList 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::allDirectSubModelNodes() const\n{\n return toQmlItemNodeList(modelNode().allDirectSubModelNodes());\n}\n\nconst QList QmlItemNode::allSubModelNodes() const\n{\n return toQmlItemNodeList(modelNode().allSubModelNodes());\n}\n\nbool QmlItemNode::hasAnySubModelNodes() const\n{\n return modelNode().hasAnySubModelNodes();\n}\n\n} \/\/QmlDesigner\nQmlDesigner: Optimize hasChildren and hasResources\/****************************************************************************\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 \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::children() const\n{\n QList 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 QmlItemNode::resources() const\n{\n QList 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 QmlItemNode::defaultPropertyChildren() const\n{\n QList 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 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 QmlModelStateGroup::allStates() const\n{\n QList 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 toModelNodeList(const QList &qmlItemNodeList)\n{\n QList modelNodeList;\n\n foreach (const QmlItemNode &qmlItemNode, qmlItemNodeList)\n modelNodeList.append(qmlItemNode.modelNode());\n\n return modelNodeList;\n}\n\nQList toQmlItemNodeList(const QList &modelNodeList)\n{\n QList 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::allDirectSubModelNodes() const\n{\n return toQmlItemNodeList(modelNode().allDirectSubModelNodes());\n}\n\nconst QList 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":"\/**\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}\nUnit tests\/**\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":"#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}setup a action to replace being updated on moving#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":"#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};\nstop propagating large if there was a binary conflict#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":"#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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\nadded formula and 0 axis#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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":"\/\/ 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 \n\n#include \"base\/basictypes.h\"\n#include \"base\/message_loop.h\"\n\n#if defined(TOOLKIT_USES_GTK)\n#include \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(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::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::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(data);\n XEvent* xev = static_cast(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(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\naura: Make MessagePumpX check that X connection is open.\/\/ 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 \n\n#include \"base\/basictypes.h\"\n#include \"base\/message_loop.h\"\n\n#if defined(TOOLKIT_USES_GTK)\n#include \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(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::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::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(data);\n XEvent* xev = static_cast(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(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":"\/\/ Day17.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\ntypedef std::pair Coordinate;\ntypedef std::pair 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 & 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 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}Day 17 part two\/\/ Day17.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n\ntypedef std::pair Coordinate;\ntypedef std::pair 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 & 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 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":"#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}Unused includes#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":"#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 \n#include \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 first_subscribe_options;\n std::unique_ptr 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_(ref_(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_(server_config);\n tcp_server->start();\n\n auto tcp_client = make_shared_(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_ 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_ &&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(\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}\nfix compilation issuw on Windows platform#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 \n#include \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 first_subscribe_options;\n std::unique_ptr 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_(ref_(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_(server_config);\n tcp_server->start();\n\n auto tcp_client = make_shared_(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_ 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_ &&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(\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":"\/*\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 \n#include \n#include \n#include \n\n#include \"pikepdf.h\"\n#include \"parsers.h\"\n\n#include \n#include \n#include \n#include \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_,\n QPDFObjectHelper>(m, \"Page\")\n .def(py::init())\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 buf(pl_buffer.getBuffer());\n auto data = reinterpret_cast(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 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}\nadd_content_token_filter keep_alive is also unnecessary\/*\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 \n#include \n#include \n#include \n\n#include \"pikepdf.h\"\n#include \"parsers.h\"\n\n#include \n#include \n#include \n#include \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_,\n QPDFObjectHelper>(m, \"Page\")\n .def(py::init())\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 buf(pl_buffer.getBuffer());\n auto data = reinterpret_cast(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 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":"\/\/ 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\nFix includes\/\/ 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":"#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 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 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::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(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::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}\nremove debug code#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 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 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::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(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::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":"#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 bytecode;\n Vector> 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) { return true; }\n\ntemplate\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 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{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(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(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(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{1, Vector(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 m_current_threads;\n Vector m_next_threads;\n\n using Utf8It = utf8::iterator;\n\n Iterator m_begin;\n Iterator m_end;\n Utf8It m_pos;\n RegexExecFlags m_flags;\n\n Vector> m_saves;\n Vector m_free_saves;\n\n Vector m_captures;\n};\n\ntemplate\nbool regex_match(It begin, It end, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n return vm.exec(begin, end, (RegexExecFlags)(flags & ~(RegexExecFlags::Search)) |\n RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate\nbool regex_match(It begin, It end, Vector& captures, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM 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\nbool regex_search(It begin, It end, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n return vm.exec(begin, end, flags | RegexExecFlags::Search | RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate\nbool regex_search(It begin, It end, Vector& captures, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM 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\nRegex: make m_current_threads and m_next_threads local variable of exec#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 bytecode;\n Vector> 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) { return true; }\n\ntemplate\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 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{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& 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(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(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(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{1, Vector(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 current_threads{Thread{m_program.bytecode.data() + start_offset, initial_saves}};\n Vector 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;\n\n Iterator m_begin;\n Iterator m_end;\n Utf8It m_pos;\n RegexExecFlags m_flags;\n\n Vector> m_saves;\n Vector m_free_saves;\n\n Vector m_captures;\n};\n\ntemplate\nbool regex_match(It begin, It end, const CompiledRegex& re, RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n return vm.exec(begin, end, (RegexExecFlags)(flags & ~(RegexExecFlags::Search)) |\n RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate\nbool regex_match(It begin, It end, Vector& captures, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM 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\nbool regex_search(It begin, It end, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM vm{re};\n return vm.exec(begin, end, flags | RegexExecFlags::Search | RegexExecFlags::AnyMatch | RegexExecFlags::NoSaves);\n}\n\ntemplate\nbool regex_search(It begin, It end, Vector& captures, const CompiledRegex& re,\n RegexExecFlags flags = RegexExecFlags::None)\n{\n ThreadedRegexVM 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":"\/\/ 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}Comments\/\/ 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":"#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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}\nExtend mefisto2d test#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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":"#pragma once\n\n#include \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\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\nstruct is_nested_execution_category : std::false_type {};\n\n\ntemplate\nstruct is_nested_execution_category> : std::true_type {};\n\n\n} \/\/ end detail\n} \/\/ end agency\n\nAdd execution_depth helper#pragma once\n\n#include \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\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\nstruct is_nested_execution_category : std::false_type {};\n\n\ntemplate\nstruct is_nested_execution_category> : std::true_type {};\n\n\ntemplate\nstruct execution_depth : std::integral_constant {};\n\n\ntemplate\nstruct execution_depth>\n : std::integral_constant<\n size_t,\n 1 + execution_depth::value\n >\n{};\n\n\n} \/\/ end detail\n} \/\/ end agency\n\n<|endoftext|>"} {"text":"\/* -*- 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 \n#include \n#include \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(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(&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(&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(&flags);\n#else\n void* flags_ptr = reinterpret_cast(&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(\"\");\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}\nClose open sockets in the destructor\/* -*- 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 \n#include \n#include \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(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(&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(&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(&flags);\n#else\n void* flags_ptr = reinterpret_cast(&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(\"\");\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":"\/***************************************************************************\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 \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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\"\nyes, now the error is not just in the changelog :)\/***************************************************************************\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 \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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":"#include \n#include \n#include \n#include \n\/\/ For speed comparisons\n#include \n#include \n#include \n#include \n\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\nusing std::vector;\n\nTEST(ProbDistributionsMultiNormalCholesky, MultiNormalVar) {\n using stan::math::var;\n Matrix y(3, 1);\n y << 2.0, -2.0, 11.0;\n Matrix mu(3, 1);\n mu << 1.0, -1.0, 3.0;\n Matrix 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 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 y(3, 1);\n y << 2.0, -2.0, 11.0;\n Matrix mu(3, 1);\n mu << 1.0, -1.0, 3.0;\n Matrix 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 L = Sigma.llt().matrixL();\n test::check_varis_on_stack(stan::math::multi_normal_cholesky_log(\n to_var(y), to_var(mu), to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), to_var(mu), L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), mu, to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), mu, L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(y, to_var(mu), to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(y, to_var(mu), L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(y, mu, to_var(L)));\n\n test::check_varis_on_stack(stan::math::multi_normal_cholesky_log(\n to_var(y), to_var(mu), to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), to_var(mu), L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), mu, to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), mu, L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(y, to_var(mu), to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(y, to_var(mu), L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(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(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> Y_dbl;\n\n for (size_t i = 0; i < R; i++) {\n Matrix y_dbl = Eigen::VectorXd::Random(C);\n Y_dbl.push_back(y_dbl);\n }\n\n Matrix mu_dbl\n = Matrix::Random(C, 1);\n\n Matrix sigma_dbl\n = Eigen::MatrixXd::Constant(C, 1, 0.01)\n + Matrix::Random(C, 1).array().abs().matrix();\n Matrix L_Sigma_dbl\n = sigma_dbl.asDiagonal()\n * stan::math::lkj_corr_cholesky_rng(C, 1.0, rng);\n\n Matrix mu_v1 = mu_dbl;\n Matrix L_Sigma_v1 = L_Sigma_dbl;\n std::vector> 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 mu_v2 = mu_dbl;\n Matrix L_Sigma_v2 = L_Sigma_dbl;\n std::vector> 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}\nchange peformacne test#include \n#include \n#include \n#include \n\/\/ For speed comparisons\n#include \n#include \n#include \n#include \n\nusing Eigen::Dynamic;\nusing Eigen::Matrix;\nusing std::vector;\n\nTEST(ProbDistributionsMultiNormalCholesky, MultiNormalVar) {\n using stan::math::var;\n Matrix y(3, 1);\n y << 2.0, -2.0, 11.0;\n Matrix mu(3, 1);\n mu << 1.0, -1.0, 3.0;\n Matrix 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 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 y(3, 1);\n y << 2.0, -2.0, 11.0;\n Matrix mu(3, 1);\n mu << 1.0, -1.0, 3.0;\n Matrix 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 L = Sigma.llt().matrixL();\n test::check_varis_on_stack(stan::math::multi_normal_cholesky_log(\n to_var(y), to_var(mu), to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), to_var(mu), L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), mu, to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), mu, L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(y, to_var(mu), to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(y, to_var(mu), L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(y, mu, to_var(L)));\n\n test::check_varis_on_stack(stan::math::multi_normal_cholesky_log(\n to_var(y), to_var(mu), to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), to_var(mu), L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), mu, to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(to_var(y), mu, L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(y, to_var(mu), to_var(L)));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(y, to_var(mu), L));\n test::check_varis_on_stack(\n stan::math::multi_normal_cholesky_log(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(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> Y_dbl;\n\n for (size_t i = 0; i < R; i++) {\n Matrix y_dbl = Eigen::VectorXd::Random(C);\n Y_dbl.push_back(y_dbl);\n }\n\n Matrix mu_dbl\n = Matrix::Random(C, 1);\n\n Matrix sigma_dbl\n = Eigen::MatrixXd::Constant(C, 1, 0.01)\n + Matrix::Random(C, 1).array().abs().matrix();\n Matrix L_Sigma_dbl\n = sigma_dbl.asDiagonal()\n * stan::math::lkj_corr_cholesky_rng(C, 1.0, rng);\n\n Matrix mu_v1 = mu_dbl;\n Matrix L_Sigma_v1 = L_Sigma_dbl;\n std::vector> 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 mu_v2 = mu_dbl;\n Matrix L_Sigma_v2 = L_Sigma_dbl;\n std::vector> 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":"\/*\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 Repository::constructor_template;\n\nvoid Repository::Init(Handle target) {\n\tHandleScope scope;\n\n\tLocal t = FunctionTemplate::New(New);\n\tconstructor_template = Persistent::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 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 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 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(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 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(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 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(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 Repository::GetRawObject(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 arg = External::New(obj);\n\tPersistent result(RawObject::constructor_template->GetFunction()->NewInstance(1, &arg));\n\treturn scope.Close(result);\n}\n\nHandle Repository::CreateRawObject(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 constructorArgs[1] = { External::New(rawObj) };\n\tHandle jsObject = RawObject::constructor_template->GetFunction()->NewInstance(1, constructorArgs);\n\n\tRawObject *rawObjObj = ObjectWrap::Unwrap(jsObject);\n\trawObjObj->repository_ = repo;\n\treturn scope.Close(jsObject);\n}\n\nHandle Repository::CreateWalker(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 constructorArgs[2] = { External::New(walker), External::New(repo) };\n\tHandle instance = RevWalker::constructor_template->GetFunction()->NewInstance(2, constructorArgs);\n\t\n\tRevWalker *walkerObject = ObjectWrap::Unwrap(instance);\n\treturn scope.Close(walkerObject->handle_);\n}\n\nHandle Repository::IndexGetter(Local, const AccessorInfo& info) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 arg = External::New(index);\n\t\tHandle instance = Index::constructor_template->GetFunction()->NewInstance(1, &arg);\n\t\trepo->index_ = ObjectWrap::Unwrap(instance);\n\t}\n\n\treturn repo->index_->handle_;\n}\n\nHandle Repository::CreateTag(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::CreateTree(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::CreateCommit(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::GetReference(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::CreateSymbolicRef(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::CreateOidRef(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::Exists(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap(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\nFixed arg count requirement in CreateSymbolicRef\/*\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 Repository::constructor_template;\n\nvoid Repository::Init(Handle target) {\n\tHandleScope scope;\n\n\tLocal t = FunctionTemplate::New(New);\n\tconstructor_template = Persistent::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 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 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 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(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 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(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 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(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 Repository::GetRawObject(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 arg = External::New(obj);\n\tPersistent result(RawObject::constructor_template->GetFunction()->NewInstance(1, &arg));\n\treturn scope.Close(result);\n}\n\nHandle Repository::CreateRawObject(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 constructorArgs[1] = { External::New(rawObj) };\n\tHandle jsObject = RawObject::constructor_template->GetFunction()->NewInstance(1, constructorArgs);\n\n\tRawObject *rawObjObj = ObjectWrap::Unwrap(jsObject);\n\trawObjObj->repository_ = repo;\n\treturn scope.Close(jsObject);\n}\n\nHandle Repository::CreateWalker(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 constructorArgs[2] = { External::New(walker), External::New(repo) };\n\tHandle instance = RevWalker::constructor_template->GetFunction()->NewInstance(2, constructorArgs);\n\t\n\tRevWalker *walkerObject = ObjectWrap::Unwrap(instance);\n\treturn scope.Close(walkerObject->handle_);\n}\n\nHandle Repository::IndexGetter(Local, const AccessorInfo& info) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 arg = External::New(index);\n\t\tHandle instance = Index::constructor_template->GetFunction()->NewInstance(1, &arg);\n\t\trepo->index_ = ObjectWrap::Unwrap(instance);\n\t}\n\n\treturn repo->index_->handle_;\n}\n\nHandle Repository::CreateTag(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::CreateTree(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::CreateCommit(const Arguments& args) {\n\tHandleScope scope;\n\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::GetReference(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::CreateSymbolicRef(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::CreateOidRef(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap(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 Repository::Exists(const Arguments& args) {\n\tHandleScope scope;\n\tRepository *repo = ObjectWrap::Unwrap(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":"\/*************************************************************************\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 \n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_\n#include \n#endif\n\n#ifndef _COMPHELPER_COMPOSEDPROPS_HXX_\n#include \n#endif\n\n#ifndef _BASEDLGS_HXX\n#include \n#endif\n\n#ifndef _SFXBRDCST_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SFXLSTNER_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SFX_CHILDWIN_HXX\n#include \n#endif\n\n#ifndef _SVDMARK_HXX \/\/autogen\n#include \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\nINTEGRATION: 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.\/*************************************************************************\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 * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _BASCTL_PROPBRW_HXX\n#define _BASCTL_PROPBRW_HXX\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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":"\/\/ 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 SampleVector::Iterator() const {\n return scoped_ptr(\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* 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\nremove redundant DCHECK that a size_t variable >= 0\/\/ 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 SampleVector::Iterator() const {\n return scoped_ptr(\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* 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":"bug fix<|endoftext|>"} {"text":"#include \"timer.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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}\nBenchmarks for getting map from Object.#include \"timer.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \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":"\/***********************************************************************\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 \n\n#include \n#include \n#include \n\n#include \n\nusing namespace mysqlpp;\nusing namespace std;\n\n\n\/\/ Compare the given string against the object inserted into an ostream.\ntemplate \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 \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 \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 \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\nAdded some verbosity to test\/datetime.cpp. Only useful for verifying visually that it does the right thing; no visible effect for end users.\/***********************************************************************\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 \n\n#include \n#include \n#include \n\n#include \n\nusing namespace mysqlpp;\nusing namespace std;\n\n\n\/\/ Compare the given string against the object inserted into a Query stream.\ntemplate \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 \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 \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 \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 \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":"\/* -*- 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 \/\/ rename(),\n#include \/\/ open()\n#include \/\/ close(), write(), read(), unlink(), truncate(), etc.\n#include \/\/ mkdir()\n#include \n#include \n#include \n#include \n#include \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 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 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\nfixes #28 Adding syscall-specific atomic lock around unlink.\/* -*- 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 \/\/ rename(),\n#include \/\/ open()\n#include \/\/ close(), write(), read(), unlink(), truncate(), etc.\n#include \/\/ mkdir()\n#include \n#include \n#include \n#include \n#include \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 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 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":"\/* _____ \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\nTypo fix\/* _____ \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":"#ifndef JEZUK_DOM_EXCEPTION_H\n#define JEZUK_DOM_EXCEPTION_H\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ C++ DOM definition\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \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\nReverted last commit#ifndef JEZUK_DOM_EXCEPTION_H\n#define JEZUK_DOM_EXCEPTION_H\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ C++ DOM definition\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n#include \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":"\/* ***************************************************************************\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 .\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 * ûУ鿴. \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修改LCUI_Widget.hpp文件编码\/* ***************************************************************************\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 .\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 * 没有,请查看:. \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":"#pragma once\n\n#ifndef RAZ_WINDOW_HPP\n#define RAZ_WINDOW_HPP\n\n#include \n#include \n#include \n#include \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;\n\nusing KeyboardCallbacks = std::vector, Input::ActionTrigger, std::function>>;\nusing MouseButtonCallbacks = std::vector, Input::ActionTrigger, std::function>>;\nusing MouseScrollCallback = std::function;\nusing MouseMoveCallback = std::tuple>;\nusing InputActions = std::unordered_map, Input::ActionTrigger>>;\nusing InputCallbacks = std::tuple;\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 static WindowPtr create(Args&&... args) { return std::make_unique(std::forward(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 actionPress,\n Input::ActionTrigger frequency = Input::ALWAYS,\n std::function actionRelease = nullptr);\n void addMouseButtonCallback(Mouse::Button button, std::function actionPress,\n Input::ActionTrigger frequency = Input::ALWAYS,\n std::function actionRelease = nullptr);\n void addMouseScrollCallback(std::function func);\n void addMouseMoveCallback(std::function 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 actionOn = nullptr, std::function actionOff = nullptr);\n void addOverlayText(const std::string& text);\n void addOverlayButton(const std::string& text, std::function action);\n void addOverlayCheckbox(const std::string& text, bool initVal, std::function actionOn, std::function 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[Utils\/Windows] Added documentation for the Window class#pragma once\n\n#ifndef RAZ_WINDOW_HPP\n#define RAZ_WINDOW_HPP\n\n#include \n#include \n#include \n#include \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, Input::ActionTrigger, std::function>>;\nusing MouseButtonCallbacks = std::vector, Input::ActionTrigger, std::function>>;\nusing MouseScrollCallback = std::function;\nusing MouseMoveCallback = std::tuple>;\nusing InputActions = std::unordered_map, Input::ActionTrigger>>;\nusing InputCallbacks = std::tuple;\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 actionPress,\n Input::ActionTrigger frequency = Input::ALWAYS,\n std::function 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 actionPress,\n Input::ActionTrigger frequency = Input::ALWAYS,\n std::function actionRelease = nullptr);\n \/\/\/ Defines an action on mouse wheel scroll.\n \/\/\/ \\param func Action to be executed when scrolling.\n void addMouseScrollCallback(std::function 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 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 actionOn = nullptr, std::function 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 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 actionOn, std::function 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":"\/*\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#endifRemove incorrect vector file<|endoftext|>"} {"text":"\/* 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 \n#include \n#include \n#include \n#include \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 \n#include \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\nBUG(1778): Fix crash in mac plugin on files without ape tag\/* 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 \n#include \n#include \n#include \n#include \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 \n#include \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":"#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 \n#include \n#include \n#include \n\nnamespace cybozu {\n\ntemplate\nsize_t RoundupBit(size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\treturn (bitLen + unitSize - 1) \/ unitSize;\n}\n\ntemplate\nT GetMaskBit(size_t bitLen)\n{\n\tassert(bitLen < sizeof(T) * 8);\n\treturn (T(1) << bitLen) - 1;\n}\n\ntemplate\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\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\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\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(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\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(bitLen); \/\/ n >= 1 because bitLen > 0\n\tconst size_t r = bitLen % unitSize;\n\tconst T mask = r > 0 ? GetMaskBit(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\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(dst, src, bitLen);\n\t\treturn;\n\t}\n\tconst size_t n = RoundupBit(bitLen); \/\/ n >= 1 because bitLen > 0\n\tconst size_t r = bitLen % unitSize;\n\tconst T mask = r ? GetMaskBit(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\nclass BitVectorT {\n\tstatic const size_t unitSize = sizeof(T) * 8;\n\tsize_t bitLen_;\n\tstd::vector 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(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(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(&v_[q], src, bitLen);\n\t\t\treturn;\n\t\t}\n\t\tT over = ShiftLeftBit(&v_[q], src, bitLen, r, v_[q] & GetMaskBit(r));\n\t\tif (RoundupBit(bitLen + r) > RoundupBit(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(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& 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(dst, &v_[q], bitLen);\n\t\t\treturn;\n\t\t}\n\t\tShiftRightBit(dst, &v_[q], bitLen + r, r);\n\t}\n\t\/*\n\t\tdst = vec[pos, pos + bitLen)\n\t*\/\n\tvoid extract(BitVectorT& 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(bitLen);\n\t\t}\n\t}\n\tbool operator==(const BitVectorT& rhs) const { return v_ == rhs.v_; }\n\tbool operator!=(const BitVectorT& rhs) const { return v_ != rhs.v_; }\n};\n\ntypedef BitVectorT BitVector;\n\n} \/\/ cybozu\nclear if decrese size#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 \n#include \n#include \n#include \n\nnamespace cybozu {\n\ntemplate\nsize_t RoundupBit(size_t bitLen)\n{\n\tconst size_t unitSize = sizeof(T) * 8;\n\treturn (bitLen + unitSize - 1) \/ unitSize;\n}\n\ntemplate\nT GetMaskBit(size_t bitLen)\n{\n\tassert(bitLen < sizeof(T) * 8);\n\treturn (T(1) << bitLen) - 1;\n}\n\ntemplate\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\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\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\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(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\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(bitLen); \/\/ n >= 1 because bitLen > 0\n\tconst size_t r = bitLen % unitSize;\n\tconst T mask = r > 0 ? GetMaskBit(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\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(dst, src, bitLen);\n\t\treturn;\n\t}\n\tconst size_t n = RoundupBit(bitLen); \/\/ n >= 1 because bitLen > 0\n\tconst size_t r = bitLen % unitSize;\n\tconst T mask = r ? GetMaskBit(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\nclass BitVectorT {\n\tstatic const size_t unitSize = sizeof(T) * 8;\n\tsize_t bitLen_;\n\tstd::vector 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(r);\n\t\t\t}\n\t\t}\n\t}\n\tvoid reserve(size_t bitLen)\n\t{\n\t\tv_.reserve(RoundupBit(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(&v_[q], src, bitLen);\n\t\t\treturn;\n\t\t}\n\t\tT over = ShiftLeftBit(&v_[q], src, bitLen, r, v_[q] & GetMaskBit(r));\n\t\tif (RoundupBit(bitLen + r) > RoundupBit(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(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& 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(dst, &v_[q], bitLen);\n\t\t\treturn;\n\t\t}\n\t\tShiftRightBit(dst, &v_[q], bitLen + r, r);\n\t}\n\t\/*\n\t\tdst = vec[pos, pos + bitLen)\n\t*\/\n\tvoid extract(BitVectorT& 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(bitLen);\n\t\t}\n\t}\n\tbool operator==(const BitVectorT& rhs) const { return v_ == rhs.v_; }\n\tbool operator!=(const BitVectorT& rhs) const { return v_ != rhs.v_; }\n};\n\ntypedef BitVectorT BitVector;\n\n} \/\/ cybozu\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud \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 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(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 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 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(1,10);\n T* t = new T[N];\n delete[] t;\n }\n \n#ifdef EIGEN_ALIGN\n {\n T* t = static_cast((T::operator new)(sizeof(T)));\n (T::operator delete)(t, sizeof(T));\n }\n \n {\n T* t = static_cast((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() );\n CALL_SUBTEST(check_dynaligned() );\n CALL_SUBTEST(check_dynaligned() );\n CALL_SUBTEST(check_dynaligned() );\n CALL_SUBTEST(check_dynaligned() );\n CALL_SUBTEST(check_dynaligned() );\n \n CALL_SUBTEST( check_custom_new_delete() );\n CALL_SUBTEST( check_custom_new_delete() );\n CALL_SUBTEST( check_custom_new_delete() );\n CALL_SUBTEST( check_custom_new_delete() );\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; iavec.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; iavec.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}\nMemory allocated on the stack is freed at the function exit, so reduce iteration count to avoid stack overflow\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2008 Gael Guennebaud \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 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(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 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 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(1,10);\n T* t = new T[N];\n delete[] t;\n }\n \n#ifdef EIGEN_ALIGN\n {\n T* t = static_cast((T::operator new)(sizeof(T)));\n (T::operator delete)(t, sizeof(T));\n }\n \n {\n T* t = static_cast((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() );\n CALL_SUBTEST(check_dynaligned() );\n CALL_SUBTEST(check_dynaligned() );\n CALL_SUBTEST(check_dynaligned() );\n CALL_SUBTEST(check_dynaligned() );\n CALL_SUBTEST(check_dynaligned() );\n \n CALL_SUBTEST( check_custom_new_delete() );\n CALL_SUBTEST( check_custom_new_delete() );\n CALL_SUBTEST( check_custom_new_delete() );\n CALL_SUBTEST( check_custom_new_delete() );\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; iavec.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; iavec.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":"\/\/\/ @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 \n#include \n#include \"xal.h\"\n\n#ifndef __APPLE__\n#include \n#else\n#include \n#include \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* prevented buffer unqueue on systemStop on iOS due to iOS OpenAL bug. it'll work ok since the source is destroyed anyway.\/\/\/ @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 \n#include \n#include \"xal.h\"\n\n#ifndef __APPLE__\n#include \n#else\n#include \n#include \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":"\/\/ 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 \n#include \n#include \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: \\\"=, \"\n \"=; ...\\\"\");\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 *peerMap) {\n using namespace silly;\n\n std::vector 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\nrpc\/config: fix incorrect default value of wal_dir.\/\/ 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 \n#include \n#include \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: \\\"=, \"\n \"=; ...\\\"\");\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* peerMap) {\n using namespace silly;\n\n std::vector 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":"\/*\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 \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 Candidates to be evaluated and modified.\n *\/\n template 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 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 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 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 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 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 Environment type.\n * @param env Environment.\n * @return Minimal error. At return time, the pool is sorted\n * using candidates scores.\n *\/\n template 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\nLate fix on genetic algorithm engine before stress test.\/*\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 \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 Candidates to be evaluated and modified.\n *\/\n template 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 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 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 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 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 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 Environment type.\n * @param env Environment.\n * @return Minimal error. At return time, the pool is sorted\n * using candidates scores.\n *\/\n template 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":"\/*\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: )\\a\/\/\n * _Qhm`] _f \"'c 1!5m\n * Visit: http:\/\/guichan.darkbits.org )Qk

      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<. a J@\\\n * this list of conditions and the j(]1uAdded missing new line\/*\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: )\\a\/\/\n * _Qhm`] _f \"'c 1!5m\n * Visit: http:\/\/guichan.darkbits.org )Qk

      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<. a J@\\\n * this list of conditions and the j(]1u"} {"text":"\/*\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}\nFix how SaveGame Music and sfx are loaded\/*\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":"\/*\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 \n#include \n#include \n#include \n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include \n#include \n\n#include \n#include \n#include \n#include \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 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 get();\n\n\t\ttemplate \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 const&);\n\n\tprivate:\n\t\tstd::queue 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 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\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr& 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(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\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr& 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\n\tstruct TORRENT_EXPORT handle_alert\n\t{\n\t\ttemplate\n\t\thandle_alert(const std::auto_ptr& 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\nadded missing include directive\/*\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 \n#include \n#include \n#include \n\n#ifdef _MSC_VER\n#pragma warning(push, 1)\n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \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 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 get();\n\n\t\ttemplate \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 const&);\n\n\tprivate:\n\t\tstd::queue 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 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\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr& 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(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\n\t\tvoid handle_alert_dispatch(\n\t\t\tconst std::auto_ptr& 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\n\tstruct TORRENT_EXPORT handle_alert\n\t{\n\t\ttemplate\n\t\thandle_alert(const std::auto_ptr& 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":"#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};added two comparers for block#pragma once\n\n#include \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;\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":"#include \n#include \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}\nnth wraped in lambda#include \n#include \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(args)...);\n };\n auto const& x = f(a, b, c);\n EXPECT_EQ(&a, &x);\n}\n}\n<|endoftext|>"} {"text":"#ifndef VSMC_CORE_WEIGHT_HPP\n\n#define VSMC_CORE_WEIGHT_HPP\n\n#include \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 \n explicit WeightSetBase (SizeType N) :\n ess_(static_cast(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 \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 \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(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 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 \n void set_log_weight (const Eigen::DenseBase &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 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 \n void add_log_weight (const Eigen::DenseBase &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\ncleanup#ifndef VSMC_CORE_WEIGHT_HPP\n#define VSMC_CORE_WEIGHT_HPP\n\n#include \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 \n explicit WeightSetBase (SizeType N) :\n ess_(static_cast(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 \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 \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(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 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 \n void set_log_weight (const Eigen::DenseBase &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 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 \n void add_log_weight (const Eigen::DenseBase &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":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \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}\nfix benchmark#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \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":"\/*******************************************************************************\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 \n#include \n#include \n#include \n#include \n#include \n\n#define RNN_MM_TRANSPOSE 1\n\n\/\/ RNN VANILLA configs\ninline std::vector get_rnn_num_layers()\n{\n \/\/ return {{1, 5, 20}};\n return {{1, 19}};\n}\n\ninline std::vector get_rnn_batchSize()\n{\n \/\/ return {128};\n return {{31, 127}};\n}\n\ninline std::vector get_rnn_seq_len()\n{\n \/\/ return {50};\n return {{3, 51}};\n}\n\ninline std::vector get_rnn_vector_len()\n{\n \/\/ return {32};\n return {{5, 31}};\n}\n\ninline std::vector 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 get_lstm_num_layers() { return {{1, 5}}; }\n\ninline std::vector get_lstm_batchSize()\n{\n \/\/ return {16};\n return {{53}};\n}\n\ninline std::vector get_lstm_seq_len()\n{\n return {25};\n \/\/ return {{2, 50}};\n}\n\ninline std::vector get_lstm_vector_len()\n{\n return {17};\n \/\/ return {{4, 32}};\n}\n\ninline std::vector 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 get_gru_num_layers() { return {{1, 5}}; }\n\ninline std::vector get_gru_batchSize()\n{\n \/\/ return {16};\n return {{53}};\n}\n\ninline std::vector get_gru_seq_len()\n{\n return {23};\n \/\/ return {{2, 50}};\n}\n\ninline std::vector get_gru_vector_len()\n{\n return {13};\n \/\/ return {{4, 32}};\n}\n\ninline std::vector get_gru_hidden_size()\n{\n return {67};\n \/\/ return {{16,64,128,256,1760,2048,2560}};\n}\n\ninline std::vector> generate_batchSeq(const int batchSize, const int seqLength)\n{\n\n int modval = 3;\n srand(modval);\n int currentval = batchSize;\n std::vector 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& 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 \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\nRemoved curly braces\/*******************************************************************************\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 \n#include \n#include \n#include \n#include \n#include \n\n#define RNN_MM_TRANSPOSE 1\n\n\/\/ RNN VANILLA configs\ninline std::vector get_rnn_num_layers()\n{\n \/\/ return {{1, 5, 20}};\n return {{1, 19}};\n}\n\ninline std::vector get_rnn_batchSize()\n{\n \/\/ return {128};\n return {{31, 127}};\n}\n\ninline std::vector get_rnn_seq_len()\n{\n \/\/ return {50};\n return {{3, 51}};\n}\n\ninline std::vector get_rnn_vector_len()\n{\n \/\/ return {32};\n return {{5, 31}};\n}\n\ninline std::vector 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 get_lstm_num_layers() { return {{1, 5}}; }\n\ninline std::vector get_lstm_batchSize()\n{\n \/\/ return {16};\n return {53};\n}\n\ninline std::vector get_lstm_seq_len()\n{\n return {25};\n \/\/ return {{2, 50}};\n}\n\ninline std::vector get_lstm_vector_len()\n{\n return {17};\n \/\/ return {{4, 32}};\n}\n\ninline std::vector 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 get_gru_num_layers() { return {{1, 5}}; }\n\ninline std::vector get_gru_batchSize()\n{\n \/\/ return {16};\n return {53};\n}\n\ninline std::vector get_gru_seq_len()\n{\n return {23};\n \/\/ return {{2, 50}};\n}\n\ninline std::vector get_gru_vector_len()\n{\n return {13};\n \/\/ return {{4, 32}};\n}\n\ninline std::vector get_gru_hidden_size()\n{\n return {67};\n \/\/ return {{16,64,128,256,1760,2048,2560}};\n}\n\ninline std::vector> generate_batchSeq(const int batchSize, const int seqLength)\n{\n\n int modval = 3;\n srand(modval);\n int currentval = batchSize;\n std::vector 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& 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 \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":"\/*\n * High level FastCGI client.\n *\n * author: Max Kellermann \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 \n\n#include \n#include \n#include \n#include \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();\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 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 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(*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}\nfcgi\/request: migrate to class Cancellable\/*\n * High level FastCGI client.\n *\n * author: Max Kellermann \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 \n\n#include \n#include \n#include \n#include \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 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 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(*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":"\/*\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 \n\n#if QT_VERSION >= 0x050000\n# include \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 ¶ms);\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 ¶ms)\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 ¶ms)\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 ¶m)\n{\n QJsonArray params;\n params.append(param);\n return createRequest(method, params);\n}\n\nQJsonRpcMessage QJsonRpcMessage::createNotification(const QString &method, const QJsonArray ¶ms)\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 ¶m)\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}\nFix QJsonObject memory leak\/*\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 \n\n#if QT_VERSION >= 0x050000\n# include \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 ¶ms);\n\n QJsonRpcMessage::Type type;\n QScopedPointer 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 ¶ms)\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 ¶ms)\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 ¶m)\n{\n QJsonArray params;\n params.append(param);\n return createRequest(method, params);\n}\n\nQJsonRpcMessage QJsonRpcMessage::createNotification(const QString &method, const QJsonArray ¶ms)\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 ¶m)\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":"#include \"bitcoinunits.h\"\n\n#include \n\nBitcoinUnits::BitcoinUnits(QObject *parent):\n QAbstractListModel(parent),\n unitlist(availableUnits())\n{\n}\n\nQList BitcoinUnits::availableUnits()\n{\n QList 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(unit));\n }\n }\n return QVariant();\n}\nupdated units#include \"bitcoinunits.h\"\n\n#include \n\nBitcoinUnits::BitcoinUnits(QObject *parent):\n QAbstractListModel(parent),\n unitlist(availableUnits())\n{\n}\n\nQList BitcoinUnits::availableUnits()\n{\n QList 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(unit));\n }\n }\n return QVariant();\n}\n<|endoftext|>"} {"text":"\/\/ 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 \n#include \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(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 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}\nperformance improvements for GUI\/\/ 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 \n#include \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(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 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":"\/\/ 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 \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \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(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())\n {\n QBrush brush = qvariant_cast(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(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 m_minimum_width;\n};\n\n#include \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}\nqt: Do not extend recent transaction width to address\/label string\/\/ 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 \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \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(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())\n {\n QBrush brush = qvariant_cast(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(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 m_minimum_width;\n};\n\n#include \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":"\/\/ 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 \n#include \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(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())\n {\n QBrush brush = qvariant_cast(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(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}\nfix a grammar problem\/\/ 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 \n#include \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(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())\n {\n QBrush brush = qvariant_cast(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(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":"\/\/ 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 \n#include \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}\nFix font size issues with splash screen\/\/ 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 \n#include \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":"\/* _______ __ __ __ ______ __ __ _______ __ __\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

      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<. a J@\\\n * this list of conditions and the j(]1uhasModalFocus())\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}\ndistributeFocusGainedEvent and distributeFocusLostEvent have been added. Focus lost events and focus gained events are now distributed to the source widget's focus listeners.\/* _______ __ __ __ ______ __ __ _______ __ __\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

      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<. a J@\\\n * this list of conditions and the j(]1uhasModalFocus())\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 focusListeners = sourceWidget->_getFocusListeners();\n\n \/\/ Send the event to all focus listeners of the widget.\n for (std::list::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 focusListeners = sourceWidget->_getFocusListeners();\n\n \/\/ Send the event to all focus listeners of the widget.\n for (std::list::iterator it = focusListeners.begin();\n it != focusListeners.end();\n ++it)\n {\n (*it)->focusGained(focusEvent);\n }\n }\n}\n<|endoftext|>"} {"text":"#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 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(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(args.Holder());\r\n string connectionString(*NanAsciiString(args[0].As()));\r\n NanCallback *callback = new NanCallback(args[1].As());\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(args.Holder());\r\n NanCallback *callback = new NanCallback(args[0].As());\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(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 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(args.Holder());\r\n string query(*NanAsciiString(args[0].As()));\r\n NanCallback *callback = new NanCallback(args[1].As());\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 tpl = NanNew(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 target) {\r\n NodbcConnection::Init();\r\n target->Set(NanNew(\"NodbcConnection\"),\r\n NanNew(nodbc_constructor)->GetFunction());\r\n}\r\n\r\nNODE_MODULE(nodbc, Init)\r\nAdd type conversions to query return values.#ifdef _WIN32\r\n #define WIN32_LEAN_AND_MEAN\r\n #include \r\n#endif\r\n\r\n#include \r\n#include \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 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(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(args.Holder());\r\n string connectionString(*NanAsciiString(args[0].As()));\r\n NanCallback *callback = new NanCallback(args[1].As());\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(args.Holder());\r\n NanCallback *callback = new NanCallback(args[0].As());\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 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(col));\r\n default:\r\n return picojson::value(result->get(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(args.Holder());\r\n string query(*NanAsciiString(args[0].As()));\r\n NanCallback *callback = new NanCallback(args[1].As());\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 tpl = NanNew(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 target) {\r\n NodbcConnection::Init();\r\n target->Set(NanNew(\"NodbcConnection\"),\r\n NanNew(nodbc_constructor)->GetFunction());\r\n}\r\n\r\nNODE_MODULE(nodbc, Init)\r\n<|endoftext|>"} {"text":"#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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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&)> handler;\n};\n\nBETTER_ENUM(entity_type, std::uint8_t,\n\tnode = exceptions::entity_type::_size(),\n\tconstant,\n\tfunction\n)\n\ntemplate\nusing unexpected_entity_exception =\n\texceptions::base_unexpected_entity_exception;\n\nconst auto usage =\nR\"(Usage:\n .\/example [options] [--] []\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{\n\t{\"pi\", 3.141592653589793238462643383279502884},\n\t{\"e\", 2.718281828459045235360287471352662497}\n};\nconst auto functions = std::unordered_map{\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\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& constants,\n\tconst std::unordered_map& 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{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{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_();\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{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(\"\")\n\t\t? options.at(\"\").asString()\n\t\t: \"\";\n\tconst auto code = options.at(\"--stdin\").asBool()\n\t\t? std::string{std::istreambuf_iterator{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::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& 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{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}\nUnifying header for all parsers: use it in the example#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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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&)> handler;\n};\n\nBETTER_ENUM(entity_type, std::uint8_t,\n\tnode = exceptions::entity_type::_size(),\n\tconstant,\n\tfunction\n)\n\ntemplate\nusing unexpected_entity_exception =\n\texceptions::base_unexpected_entity_exception;\n\nconst auto usage =\nR\"(Usage:\n .\/example [options] [--] []\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{\n\t{\"pi\", 3.141592653589793238462643383279502884},\n\t{\"e\", 2.718281828459045235360287471352662497}\n};\nconst auto functions = std::unordered_map{\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\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& constants,\n\tconst std::unordered_map& 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{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{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_();\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{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(\"\")\n\t\t? options.at(\"\").asString()\n\t\t: \"\";\n\tconst auto code = options.at(\"--stdin\").asBool()\n\t\t? std::string{std::istreambuf_iterator{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::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& 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{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":"\/**\n ** \\file rewrite\/rescoper.cc\n ** \\brief Implementation of rewrite::Rescoper.\n *\/\n\n#include \n#include \n#include \n#include \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();\n if (stm && stm->flavor_get() == ast::flavor_comma)\n {\n if (ast::rDeclaration dec =\n stm->expression_get().unsafe_cast())\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}\nUnscope variables declared as '&' operands.\/**\n ** \\file rewrite\/rescoper.cc\n ** \\brief Implementation of rewrite::Rescoper.\n *\/\n\n#include \n#include \n#include \n#include \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())\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();\n if (stm && stm->flavor_get() == ast::flavor_comma)\n {\n if (ast::rDeclaration dec =\n stm->expression_get().unsafe_cast())\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":"\/* 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\nDon't take into account ping loss for now\/* 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":"#include \n#include \n#include \n#include \n\nusing namespace std;\n\nint main()\n{\n\tvector 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>temp1 && fin2>>temp2 && fin2>>temp3)\n\t\t{\n\t\t\tfout1<Two more directories#include \n#include \n#include \n#include \n\nusing namespace std;\n\nint main()\n{\n\tvector 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>temp1 && fin2>>temp2 && fin2>>temp3)\n\t\t{\n\t\t\tfout1<"} {"text":"\/*\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 \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \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(\"pose\", 100);\n std::string connec_nm = server_ip + \":\" + boost::lexical_cast(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(\"vrpn_server_ip\", vrpn_server_ip, std::string());\n nh.param(\"vrpn_port\", vrpn_port, 3883);\n nh.param(\"vrpn_coordinate_system\", corrdinate_system_string, \"vicon\");\n\n\n std::cout<<\"vrpn_server_ip:\"<clean up\/*\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 \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \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(\"pose\", 100);\n std::string connec_nm = server_ip + \":\" + boost::lexical_cast(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(\"vrpn_server_ip\", vrpn_server_ip, std::string());\n nh.param(\"vrpn_port\", vrpn_port, 3883);\n nh.param(\"vrpn_coordinate_system\", corrdinate_system_string, \"vicon\");\n\n\n std::cout<<\"vrpn_server_ip:\"<"} {"text":"#ifndef UTILS_UTILS_HPP\n#define UTILS_UTILS_HPP\n\n\n#include \n#include \n#include \n#include \n\n#include \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(), \"\", \"(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(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(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\nAdded env->ExceptionDescribe() to DETAIL_JOINT_JAVA_TERMINATE_ON_EXCEPTION macro#ifndef UTILS_UTILS_HPP\n#define UTILS_UTILS_HPP\n\n\n#include \n#include \n#include \n#include \n\n#include \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(), \"\", \"(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(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(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":"\/\/ 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 \n#include \n#include \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\", alert_doc, no_init)\n .def(\n \"msg\", &alert::msg, return_value_policy()\n , alert_msg_doc\n )\n .def(\"severity\", &alert::severity, alert_severity_doc)\n .def(\n \"__str__\", &alert::msg, return_value_policy()\n , alert_msg_doc\n )\n ;\n\n enum_(\"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_, noncopyable>(\n \"listen_failed_alert\", listen_failed_alert_doc, no_init\n );\n\n class_, noncopyable>(\n \"file_error_alert\", file_error_alert_doc, no_init\n )\n .def_readonly(\"handle\", &file_error_alert::handle)\n ;\n\n class_, noncopyable>(\n \"tracker_announce_alert\", tracker_announce_alert_doc, no_init\n )\n .def_readonly(\"handle\", &tracker_announce_alert::handle)\n ;\n\n class_, 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_, noncopyable>(\n \"tracker_reply_alert\", tracker_reply_alert_doc, no_init\n )\n .def_readonly(\"handle\", &tracker_reply_alert::handle)\n ;\n\n class_, noncopyable>(\n \"tracker_warning_alert\", tracker_warning_alert_doc, no_init\n )\n .def_readonly(\"handle\", &tracker_warning_alert::handle)\n ;\n\n class_, noncopyable>(\n \"url_seed_alert\", url_seed_alert_doc, no_init\n )\n .def_readonly(\"url\", &url_seed_alert::url)\n ;\n\n class_, 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_, 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_, 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_, 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_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_, noncopyable>(\n \"torrent_finished_alert\", torrent_finished_alert_doc, no_init\n )\n .def_readonly(\"handle\", &torrent_finished_alert::handle)\n ;\n\n class_, noncopyable>(\n \"metadata_failed_alert\", metadata_failed_alert_doc, no_init\n )\n .def_readonly(\"handle\", &metadata_failed_alert::handle)\n ;\n\n class_, noncopyable>(\n \"metadata_received_alert\", metadata_received_alert_doc, no_init\n )\n .def_readonly(\"handle\", &metadata_received_alert::handle)\n ;\n\n class_, noncopyable>(\n \"fastresume_rejected_alert\", fastresume_rejected_alert_doc, no_init\n )\n .def_readonly(\"handle\", &fastresume_rejected_alert::handle)\n ;\n}\n\nfixed typo\/\/ 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 \n#include \n#include \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\", alert_doc, no_init)\n .def(\n \"msg\", &alert::msg, return_value_policy()\n , alert_msg_doc\n )\n .def(\"severity\", &alert::severity, alert_severity_doc)\n .def(\n \"__str__\", &alert::msg, return_value_policy()\n , alert_msg_doc\n )\n ;\n\n enum_(\"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_, noncopyable>(\n \"listen_failed_alert\", listen_failed_alert_doc, no_init\n );\n\n class_, noncopyable>(\n \"file_error_alert\", file_error_alert_doc, no_init\n )\n .def_readonly(\"handle\", &file_error_alert::handle)\n ;\n\n class_, noncopyable>(\n \"tracker_announce_alert\", tracker_announce_alert_doc, no_init\n )\n .def_readonly(\"handle\", &tracker_announce_alert::handle)\n ;\n\n class_, 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_, noncopyable>(\n \"tracker_reply_alert\", tracker_reply_alert_doc, no_init\n )\n .def_readonly(\"handle\", &tracker_reply_alert::handle)\n ;\n\n class_, noncopyable>(\n \"tracker_warning_alert\", tracker_warning_alert_doc, no_init\n )\n .def_readonly(\"handle\", &tracker_warning_alert::handle)\n ;\n\n class_, noncopyable>(\n \"url_seed_alert\", url_seed_alert_doc, no_init\n )\n .def_readonly(\"url\", &url_seed_alert::url)\n ;\n\n class_, 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_, 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_, 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_, 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_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_, noncopyable>(\n \"torrent_finished_alert\", torrent_finished_alert_doc, no_init\n )\n .def_readonly(\"handle\", &torrent_finished_alert::handle)\n ;\n\n class_, noncopyable>(\n \"metadata_failed_alert\", metadata_failed_alert_doc, no_init\n )\n .def_readonly(\"handle\", &metadata_failed_alert::handle)\n ;\n\n class_, noncopyable>(\n \"metadata_received_alert\", metadata_received_alert_doc, no_init\n )\n .def_readonly(\"handle\", &metadata_received_alert::handle)\n ;\n\n class_, 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":"\/******************************************************************************\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 \n\n#include \n#include \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\nCRC unit tests\/******************************************************************************\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 \n\n#include \n#include \n#include \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":"#include \"greedy_solver.h\"\n\n#include \n#include \n#include \n#include \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& unit_caps = n->unit_capacities[a];\n const std::vector& group_caps = n->group->capacities();\n std::vector 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::max()) {\n caps.push_back(std::numeric_limits::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());\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& nodes = prs->nodes();\n std::stable_sort(nodes.begin(), nodes.end(), AvgPrefComp);\n\n std::vector::iterator req_it = nodes.begin();\n double target = prs->qty();\n double match = 0;\n\n ExchangeNode::Ptr u, v;\n std::vector::const_iterator arc_it;\n std::vector 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& arcs = graph_->node_arc_map().at(*req_it);\n sorted = std::vector(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& unit_caps = n->unit_capacities[a];\n std::vector& 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::max()) ?\n std::numeric_limits::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::iterator n_it;\n std::map >::iterator c_it;\n std::map::iterator p_it;\n std::vector::iterator rg_it;\n std::vector::iterator sg_it;\n double min_cap, pref, coeff;\n\n double max_coeff = std::numeric_limits::min();\n double min_unit_cap = std::numeric_limits::max();\n\n for (sg_it = graph_->supply_groups().begin();\n sg_it != graph_->supply_groups().end();\n ++sg_it) {\n std::vector& nodes = (*sg_it)->nodes();\n for (n_it = nodes.begin(); n_it != nodes.end(); ++n_it) {\n \/\/ update min_unit_cap\n std::map >::iterator c_it;\n std::map >& caps = (*n_it)->unit_capacities;\n for (c_it = caps.begin(); c_it != caps.end(); ++c_it) {\n std::vector& 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& nodes = (*rg_it)->nodes();\n for (n_it = nodes.begin(); n_it != nodes.end(); ++n_it) {\n \/\/ update min_unit_cap\n std::map >::iterator c_it;\n std::map >& caps = (*n_it)->unit_capacities;\n for (c_it = caps.begin(); c_it != caps.end(); ++c_it) {\n std::vector& 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& 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\nerrant o#include \"greedy_solver.h\"\n\n#include \n#include \n#include \n#include \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& unit_caps = n->unit_capacities[a];\n const std::vector& group_caps = n->group->capacities();\n std::vector 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::max()) {\n caps.push_back(std::numeric_limits::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());\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& nodes = prs->nodes();\n std::stable_sort(nodes.begin(), nodes.end(), AvgPrefComp);\n\n std::vector::iterator req_it = nodes.begin();\n double target = prs->qty();\n double match = 0;\n\n ExchangeNode::Ptr u, v;\n std::vector::const_iterator arc_it;\n std::vector 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& arcs = graph_->node_arc_map().at(*req_it);\n sorted = std::vector(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& unit_caps = n->unit_capacities[a];\n std::vector& 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::max()) ?\n std::numeric_limits::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::iterator n_it;\n std::map >::iterator c_it;\n std::map::iterator p_it;\n std::vector::iterator rg_it;\n std::vector::iterator sg_it;\n double min_cap, pref, coeff;\n\n double max_coeff = std::numeric_limits::min();\n double min_unit_cap = std::numeric_limits::max();\n\n for (sg_it = graph_->supply_groups().begin();\n sg_it != graph_->supply_groups().end();\n ++sg_it) {\n std::vector& nodes = (*sg_it)->nodes();\n for (n_it = nodes.begin(); n_it != nodes.end(); ++n_it) {\n \/\/ update min_unit_cap\n std::map >::iterator c_it;\n std::map >& caps = (*n_it)->unit_capacities;\n for (c_it = caps.begin(); c_it != caps.end(); ++c_it) {\n std::vector& 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& nodes = (*rg_it)->nodes();\n for (n_it = nodes.begin(); n_it != nodes.end(); ++n_it) {\n \/\/ update min_unit_cap\n std::map >::iterator c_it;\n std::map >& caps = (*n_it)->unit_capacities;\n for (c_it = caps.begin(); c_it != caps.end(); ++c_it) {\n std::vector& 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& 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":"gui: fix non-gui build missing symbols<|endoftext|>"} {"text":"\/\/ 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\nBits for reading APICID from a cpuid register\/\/ 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":"#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& 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}Optimize isValidSymbolCharacter().#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& 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":"\/*\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 \n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include \n#include \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 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\nmake test_utp more likely to pass\/*\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 \n#include \n\n#include \"test.hpp\"\n#include \"setup_transfer.hpp\"\n#include \n#include \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 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":"#include \n#include \n#include \n#include \n\n#include \"errors.hpp\"\n#include \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 _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(f)),\n std::istreambuf_iterator());\n\n res_out->code = 200;\n\n return;\n\nINTERNAL_ERROR:\n res_out->code = 500;\n}\nremove useless branch#include \n#include \n#include \n#include \n\n#include \"errors.hpp\"\n#include \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 _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(f)),\n std::istreambuf_iterator());\n\n res_out->code = 200;\n\n return;\n\nINTERNAL_ERROR:\n res_out->code = 500;\n}\n<|endoftext|>"} {"text":"#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}\nfix core from last push.#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":"\/*\n * High level HTTP client.\n *\n * author: Max Kellermann \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 \n\n#include \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(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(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}\nhttp_request: use tcp_stock_item_get_address()\/*\n * High level HTTP client.\n *\n * author: Max Kellermann \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 \n\n#include \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(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(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":"#include \"statement.hpp\"\nnamespace backend {\n\nret::ret(const std::shared_ptr &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 &lhs,\n const std::shared_ptr &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 &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 &id,\n const std::shared_ptr &args,\n const std::shared_ptr &stmts,\n const std::shared_ptr &type,\n const std::shared_ptr &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 cond,\n std::shared_ptr then,\n std::shared_ptr 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 > &&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\nStraggler.#include \"statement.hpp\"\nnamespace backend {\n\nret::ret(const std::shared_ptr &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 &lhs,\n const std::shared_ptr &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 &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 &id,\n const std::shared_ptr &args,\n const std::shared_ptr &stmts,\n const std::shared_ptr &type,\n const std::shared_ptr &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 procedure::p_type(void) const {\n return m_type;\n}\n\nstd::shared_ptr 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 cond,\n std::shared_ptr then,\n std::shared_ptr 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 > &&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":"#include \n#include \n#include \n#include \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}\nFixed prompt functions#include \n#include \n#include \n#include \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":"#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 \r\n#include \r\n#include \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> 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\nrename#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 \r\n#include \r\n#include \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> 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":"\/* 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 \n#include \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 \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 \n#include \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}\nEnhance getCPUTime for Unix environments.\/* 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 \n\n#ifdef WIN32\n# include \n# include \n#else\n# include \n# include \n#endif \/\/ WIN32\n\n#include \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":"#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(\"task\/gate\/alignment\", 1, &AlignmentController::AlignmentCB, this);\n command_sub = nh.subscribe(\"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(\"command\/accel\/linear\/x\", 1);\n y_pub = nh.advertise(\"command\/accel\/linear\/y\", 1);\n z_pub = nh.advertise(\"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(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\/\/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}\nAdded todo notes in alignment_controller#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(\"task\/gate\/alignment\", 1, &AlignmentController::AlignmentCB, this);\n command_sub = nh.subscribe(\"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(\"command\/accel\/linear\/x\", 1);\n y_pub = nh.advertise(\"command\/accel\/linear\/y\", 1);\n z_pub = nh.advertise(\"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(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\/\/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":"#include \"..\/tlang.h\"\n#include \n#include \n#include \n#include \n\nTC_NAMESPACE_BEGIN\n\nusing namespace Tlang;\n\nauto cnn = [](std::vector 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(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(dx + 1, dy + 1, dz + 1,\n c_in * num_ch2 + c_out) = 1.f \/ 16.f;\n } else {\n weights.val(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(i, j, k, 0);\n if (layer2.val(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(i \/ scale, j \/ scale, k, channel);\n } else {\n dx = layer2.val(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\noptimize dilate#include \"..\/tlang.h\"\n#include \n#include \n#include \n#include \n\nTC_NAMESPACE_BEGIN\n\nusing namespace Tlang;\n\nauto cnn = [](std::vector 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(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(dx + 1, dy + 1, dz + 1,\n c_in * num_ch2 + c_out) = 1.f \/ 16.f;\n } else {\n weights.val(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(i, j, k, 0);\n if (layer2.val(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(i \/ scale, j \/ scale, k, channel);\n } else {\n dx = layer2.val(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":"\/*************************************************************************\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 \n#endif\n\n#ifndef _SV_GEN_HXX\n#include \n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \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_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\nINTEGRATION: 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\/*************************************************************************\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 \n#endif\n\n#ifndef _SV_GEN_HXX\n#include \n#endif\n\n#ifndef SC_SCGLOB_HXX\n#include \"global.hxx\"\n#endif\n\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \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_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":"\/*\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 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 \n *\/\n\n#include \n#include \n#include \n#include \n#include \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}\nSnake de prueba utilizando lo desarrollado en los últimos días\/*\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 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 \n *\/\n\n#include \n#include \n#include \n#include \n#include \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":"\/*=========================================================================\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 \n#include \n#include \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& movvars_in);\n\n \/** runtime selection of writer for MLsol *\/\n static std::auto_ptr build(const WriterEnum format, MultiLevelSolution * ml_sol);\n\n \/** runtime selection of writer for MLmesh *\/\n static std::auto_ptr 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\"< &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 _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\nfixed issues\/*=========================================================================\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 \n#include \n#include \n#include \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& movvars_in);\n\n \/** runtime selection of writer for MLsol *\/\n static std::auto_ptr build(const WriterEnum format, MultiLevelSolution * ml_sol);\n\n \/** runtime selection of writer for MLmesh *\/\n static std::auto_ptr 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\"< &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 _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":"\/*\n * This file is part of QZeitgeist.\n *\n * Copyright (C) 2013 David Rosca \n *\n * This 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 \n}\n\n#include \"timerange.h\"\n#include \"timerange_p.h\"\n#include \n#include \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::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\nFixed TimeRange::timeRangeFromNow.\/*\n * This file is part of QZeitgeist.\n *\n * Copyright (C) 2013 David Rosca \n *\n * This 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 \n}\n\n#include \"timerange.h\"\n#include \"timerange_p.h\"\n#include \n#include \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::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::max());\n}\n\n}; \/\/ namespace QZeitgeist\n\n<|endoftext|>"} {"text":"#ifndef LIFOCache_HPP\n#define LIFOCache_HPP\n\n#include \n#include \n#include \n#include \n#include \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 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 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\nmulti-thread get#ifndef LIFOCache_HPP\n#define LIFOCache_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \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 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 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":"\/*\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}adding input category UI\/*\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":"#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(&nMotif)->default_value(-1), \"[integer] # of motif to load\"\n\t\t\t\"non-positive means load all)\")\n\t\t(\"nGraph\", value(&nGraph)->default_value(-1), \"[integer] # of graph to load\"\n\t\t\t\"non-positive means load all)\")\n\t\t(\"nSkipMotif\",value(&nSkipMotif)->default_value(0),\"[integer] skip the first k valid motifs.\")\n\t\t(\"nSkipGraph\", value(&nSkipGraph)->default_value(0), \"[integer] skip the first k valid graph.\")\n\t\t(\"motifPath\", value(&motifPath), \"the folder for motifs (input)\")\n\t\t(\"motifPattern\", value(&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(&graphPath), \"the folder for graph data (input)\")\n\t\t(\"graphTypePos\", value>(&graphTypePos)->multitoken(), \"the type(s) of positive graph\")\n\t\t(\"graphTypeNeg\", value>(&graphTypeNeg)->multitoken()->default_value(vector(1, 0), \"0\"),\n\t\t\t\"the type(s) of negative graphs\")\n\t\t\/\/(\"thrsldMotifSub\", value(&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>(&motifTestMethod)->multitoken(), MotifTester::usage.c_str())\n\t\t(\"logFile\", value(&logFile), \"the file for detailed motif checking log (output)\")\n\t\t(\"outputFile\", value(&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\nadd input checking#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(&nMotif)->default_value(-1), \"[integer] # of motif to load\"\n\t\t\t\"non-positive means load all)\")\n\t\t(\"nGraph\", value(&nGraph)->default_value(-1), \"[integer] # of graph to load\"\n\t\t\t\"non-positive means load all)\")\n\t\t(\"nSkipMotif\",value(&nSkipMotif)->default_value(0),\"[integer] skip the first k valid motifs.\")\n\t\t(\"nSkipGraph\", value(&nSkipGraph)->default_value(0), \"[integer] skip the first k valid graph.\")\n\t\t(\"motifPath\", value(&motifPath), \"the folder for motifs (input)\")\n\t\t(\"motifPattern\", value(&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(&graphPath), \"the folder for graph data (input)\")\n\t\t(\"graphTypePos\", value>(&graphTypePos)->multitoken(), \"the type(s) of positive graph\")\n\t\t(\"graphTypeNeg\", value>(&graphTypeNeg)->multitoken()->default_value(vector(1, 0), \"0\"),\n\t\t\t\"the type(s) of negative graphs\")\n\t\t\/\/(\"thrsldMotifSub\", value(&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>(&motifTestMethod)->multitoken(), MotifTester::usage.c_str())\n\t\t(\"logFile\", value(&logFile), \"the file for detailed motif checking log (output)\")\n\t\t(\"outputFile\", value(&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":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 v;\n \/\/Defines a tokenizer type that seperates cmdLine by spaces\n typedef tokenizer > tokenizer;\n char_separator 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 > 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 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 analyze_split(vector& v)\n {\n vector 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 >organize_commands(vector whole_command)\n {\n \/\/Vector to be returned\n vector > commands;\n \/\/Vector of a single command that is constantly pushed into the vector above.\n vector 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(vectorcmd)\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};Fixed shell bugs#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 v;\n \/\/Defines a tokenizer type that seperates cmdLine by spaces\n typedef tokenizer > tokenizer;\n char_separator 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 > 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 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 analyze_split(vector& v)\n {\n vector 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 >organize_commands(vector whole_command)\n {\n \/\/Vector to be returned\n vector > commands;\n \/\/Vector of a single command that is constantly pushed into the vector above.\n vector 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(vectorcmd)\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":"#include \"iotsaRequest.h\"\n#include \n#ifdef ESP32\n#include \n#else\n#include \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:
      \\n\";\n#ifdef ESP32\n message += \"Root CA cert (https only)<\/i>:
      \\n\";\n#else\n message += \"Fingerprint (https only)<\/i>:
      \\n\";\n#endif\n\n message += \"Bearer token (optional)<\/i>:
      \\n\";\n message += \"Credentials (optional, user:pass)<\/i>:
      \\n\";\n}\n\nvoid IotsaRequest::formHandler(String& message, String& text, String& f_name) { \n message += \"Activation URL:
      \\n\";\n#ifdef ESP32\n message += \"Root CA cert (https only)<\/i>:
      \\n\";\n\n message += \"Bearer token (optional)<\/i>:
      \\n\";\n\n message += \"Credentials (optional, user:pass)<\/i>:
      \\n\";\n}\n\nvoid IotsaRequest::formHandlerTH(String& message) {\n message += \"

URL<\/th>\" SSL_INFO_NAME \"<\/th>credentials<\/th>token<\/th>\";\n}\n\nvoid IotsaRequest::formHandlerTD(String& message) {\n message += \"\";\n message += url;\n message += \"<\/td>\";\n message += sslInfo;\n message += \"<\/td>\";\n message += credentials;\n message += \"<\/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()) return false;\n bool any = false;\n const JsonObject& reqObj = request.as();\n if (reqObj.containsKey(\"url\")) {\n any = true;\n url = reqObj[\"url\"].as();\n }\n if (reqObj.containsKey(SSL_INFO_NAME)) {\n any = true;\n sslInfo = reqObj[SSL_INFO_NAME].as();\n }\n if (reqObj.containsKey(\"credentials\")) {\n any = true;\n credentials = reqObj[\"credentials\"].as();\n }\n if (reqObj.containsKey(\"token\")) {\n any = true;\n token = reqObj[\"token\"].as();\n }\n return any;\n}\n#endif \/\/ IOTSA_WITH_APIBug fixes to iotsaRequest#include \"iotsaRequest.h\"\n#include \n#ifdef ESP32\n#include \n#else\n#include \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:
\\n\";\n#ifdef ESP32\n message += \"Root CA cert (https only)<\/i>:
\\n\";\n#else\n message += \"Fingerprint (https only)<\/i>:
\\n\";\n#endif\n\n message += \"Bearer token (optional)<\/i>:
\\n\";\n message += \"Credentials (optional, user:pass)<\/i>:
\\n\";\n}\n\nvoid IotsaRequest::formHandler(String& message, String& text, String& f_name) { \n message += \"Activation URL:
\\n\";\n#ifdef ESP32\n message += \"Root CA cert (https only)<\/i>:
\\n\";\n\n message += \"Bearer token (optional)<\/i>:
\\n\";\n\n message += \"Credentials (optional, user:pass)<\/i>:
\\n\";\n}\n\nvoid IotsaRequest::formHandlerTH(String& message) {\n message += \"
URL<\/th>\" SSL_INFO_NAME \"<\/th>credentials<\/th>token<\/th>\";\n}\n\nvoid IotsaRequest::formHandlerTD(String& message) {\n message += \"\";\n message += url;\n message += \"<\/td>\";\n message += sslInfo;\n message += \"<\/td>\";\n message += credentials;\n message += \"<\/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()) return false;\n bool any = false;\n const JsonObject& reqObj = request.as();\n if (reqObj.containsKey(\"url\")) {\n any = true;\n url = reqObj[\"url\"].as();\n }\n if (reqObj.containsKey(SSL_INFO_NAME)) {\n any = true;\n sslInfo = reqObj[SSL_INFO_NAME].as();\n }\n if (reqObj.containsKey(\"credentials\")) {\n any = true;\n credentials = reqObj[\"credentials\"].as();\n }\n if (reqObj.containsKey(\"token\")) {\n any = true;\n token = reqObj[\"token\"].as();\n }\n return any;\n}\n#endif \/\/ IOTSA_WITH_API<|endoftext|>"} {"text":"\/*\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}\nTurned on eol strip by default.\/*\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":"removed energy normalization<|endoftext|>"} {"text":"\/*=========================================================================\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 \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( 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( 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( 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}\nENH: better testing and reporting (entropies, per processor, etc.)\/*=========================================================================\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 \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( 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( 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( 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":"\/******************************************************************************\n * Copyright (C) 2018 Kitsune Ral \n *\n * This 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 \n#include \n#include \n#include \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\"(\\1\\2<\/a>)\"));\n htmlEscapedText.replace(FullUrlRegExp,\n QStringLiteral(R\"(\\1<\/a>)\"));\n}\n\nQString QMatrixClient::prettyPrint(const QString& plainText)\n{\n auto pt = QStringLiteral(\"\") +\n plainText.toHtmlEscaped() + QStringLiteral(\"<\/span>\");\n pt.replace('\\n', QStringLiteral(\"\"));\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, int>::value,\n \"Test fn_return_t<>\");\n\nvoid f1(int);\nstatic_assert(function_traits::arg_number == 1,\n \"Test fn_arg_number\");\n\nvoid f2(int, QString);\nstatic_assert(std::is_same, QString>::value,\n \"Test fn_arg_t<>\");\n\nstruct S { int mf(); };\nstatic_assert(is_callable_v, \"Test member function\");\nstatic_assert(returns(), \"Test returns<> with member function\");\n\nstruct Fo { int operator()(); };\nstatic_assert(is_callable_v, \"Test is_callable<> with function object\");\nstatic_assert(function_traits::arg_number == 0, \"Test function object\");\nstatic_assert(std::is_same, int>::value,\n \"Test return type of function object\");\n\nstruct Fo1 { void operator()(int); };\nstatic_assert(function_traits::arg_number == 1, \"Test function object 1\");\nstatic_assert(is_callable_v, \"Test is_callable<> with function object 1\");\nstatic_assert(std::is_same, 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, \"Test is_callable_v<> with lambda\");\nstatic_assert(std::is_same, int>::value,\n \"Test fn_return_t<> with lambda\");\n#endif\n\ntemplate \nstruct fn_object\n{\n static int smf(double) { return 0; }\n};\ntemplate <>\nstruct fn_object\n{\n void operator()(QString);\n};\nstatic_assert(is_callable_v>, \"Test function object\");\nstatic_assert(returns>(),\n \"Test returns<> with function object\");\nstatic_assert(!is_callable_v>, \"Test non-function object\");\n\/\/ FIXME: These two don't work\n\/\/static_assert(is_callable_v::smf)>,\n\/\/ \"Test static member function\");\n\/\/static_assert(returns::smf)>(),\n\/\/ \"Test returns<> with static member function\");\n\ntemplate \nQString ft(T&&);\nstatic_assert(std::is_same)>, QString&&>(),\n \"Test function templates\");\n\n#ifdef Q_CC_CLANG\n#pragma clang diagnostic pop\n#endif\nLinkify Matrix identifiers\/******************************************************************************\n * Copyright (C) 2018 Kitsune Ral \n *\n * This 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 \n#include \n#include \n#include \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\"(\\1\\2<\/a>)\"));\n htmlEscapedText.replace(FullUrlRegExp,\n QStringLiteral(R\"(\\1<\/a>)\"));\n htmlEscapedText.replace(MxIdRegExp,\n QStringLiteral(R\"(\\1\\2<\/a>)\"));\n}\n\nQString QMatrixClient::prettyPrint(const QString& plainText)\n{\n auto pt = QStringLiteral(\"\") +\n plainText.toHtmlEscaped() + QStringLiteral(\"<\/span>\");\n pt.replace('\\n', QStringLiteral(\"\"));\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, int>::value,\n \"Test fn_return_t<>\");\n\nvoid f1(int);\nstatic_assert(function_traits::arg_number == 1,\n \"Test fn_arg_number\");\n\nvoid f2(int, QString);\nstatic_assert(std::is_same, QString>::value,\n \"Test fn_arg_t<>\");\n\nstruct S { int mf(); };\nstatic_assert(is_callable_v, \"Test member function\");\nstatic_assert(returns(), \"Test returns<> with member function\");\n\nstruct Fo { int operator()(); };\nstatic_assert(is_callable_v, \"Test is_callable<> with function object\");\nstatic_assert(function_traits::arg_number == 0, \"Test function object\");\nstatic_assert(std::is_same, int>::value,\n \"Test return type of function object\");\n\nstruct Fo1 { void operator()(int); };\nstatic_assert(function_traits::arg_number == 1, \"Test function object 1\");\nstatic_assert(is_callable_v, \"Test is_callable<> with function object 1\");\nstatic_assert(std::is_same, 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, \"Test is_callable_v<> with lambda\");\nstatic_assert(std::is_same, int>::value,\n \"Test fn_return_t<> with lambda\");\n#endif\n\ntemplate \nstruct fn_object\n{\n static int smf(double) { return 0; }\n};\ntemplate <>\nstruct fn_object\n{\n void operator()(QString);\n};\nstatic_assert(is_callable_v>, \"Test function object\");\nstatic_assert(returns>(),\n \"Test returns<> with function object\");\nstatic_assert(!is_callable_v>, \"Test non-function object\");\n\/\/ FIXME: These two don't work\n\/\/static_assert(is_callable_v::smf)>,\n\/\/ \"Test static member function\");\n\/\/static_assert(returns::smf)>(),\n\/\/ \"Test returns<> with static member function\");\n\ntemplate \nQString ft(T&&);\nstatic_assert(std::is_same)>, QString&&>(),\n \"Test function templates\");\n\n#ifdef Q_CC_CLANG\n#pragma clang diagnostic pop\n#endif\n<|endoftext|>"} {"text":"\/*=========================================================================\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 \n#include \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}\nCOMP: disable warning for VS\/*=========================================================================\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 \n#include \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":"#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\nSigned-off-by: mrlitong #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":"\/\/\n\/\/ Copyright (C) 2012\n\/\/ Alessio Sclocco \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 .\n\/\/\n\n#include \nusing std::cout;\nusing std::cerr;\nusing std::endl;\n#include \nusing std::string;\n#include \nusing std::vector;\n#include \nusing std::exception;\n#include \nusing std::fixed;\nusing std::setprecision;\n#include \nusing std::numeric_limits;\n#include \n#include \n\n#include \nusing isa::utils::ArgumentList;\n#include \nusing AstroData::Observation;\n#include \nusing isa::OpenCL::initializeOpenCL;\n#include \nusing isa::OpenCL::CLData;\n#include \nusing isa::utils::same;\n#include \nusing PulsarSearch::Folding;\n#include \nusing PulsarSearch::folding;\n#include \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(\"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(\"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\nI was allocating too much memory for the counters.\/\/\n\/\/ Copyright (C) 2012\n\/\/ Alessio Sclocco \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 .\n\/\/\n\n#include \nusing std::cout;\nusing std::cerr;\nusing std::endl;\n#include \nusing std::string;\n#include \nusing std::vector;\n#include \nusing std::exception;\n#include \nusing std::fixed;\nusing std::setprecision;\n#include \nusing std::numeric_limits;\n#include \n#include \n\n#include \nusing isa::utils::ArgumentList;\n#include \nusing AstroData::Observation;\n#include \nusing isa::OpenCL::initializeOpenCL;\n#include \nusing isa::OpenCL::CLData;\n#include \nusing isa::utils::same;\n#include \nusing PulsarSearch::Folding;\n#include \nusing PulsarSearch::folding;\n#include \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(\"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(\"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":"\/*\n * Copyright (C) 2012\n * Alessio Sclocco \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 .\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \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(\"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(\"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\nTypo.\/*\n * Copyright (C) 2012\n * Alessio Sclocco \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 .\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 \n#include \n#include \n#include \n#include \n#include \n#include \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(\"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(\"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":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\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();\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\/ 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\/ 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}\nFailedServer jobs can report when last FailedLeader has been processed\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\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();\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\/ 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\/ 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":"\/*\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\nGLES2 render system: removed end of line chars from the compile result to log function - - so there will be less empty lines in the log.\/*\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":"#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::scan(std::istream& is)\n throw(syntax_error)\n {\n std::vector tokens;\n std::string buffer;\n\n for (std::istreambuf_iterator 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}\nsimplify scanning routine#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::scan(std::istream& is)\n throw(syntax_error)\n {\n std::vector tokens;\n std::string buffer;\n\n for (std::istreambuf_iterator 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":"#include \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}\nstuff#include \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":"#ifndef PONG_DEFS_HPP_\n#define PONG_DEFS_HPP_\n\n#include \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_ *\/\nRemove unused enum#ifndef PONG_DEFS_HPP_\n#define PONG_DEFS_HPP_\n\n#include \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":"#ifndef _SNARKFRONT_POWERS_OF_2_HPP_\n#define _SNARKFRONT_POWERS_OF_2_HPP_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \/\/ snarklib\n\nnamespace snarkfront {\n\n\/\/ look up table for powers of 2 for BigInt\/field\/group\ntemplate \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& 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 m_lut; \/\/ index -> T(2^index)\n};\n\n\/\/ convert Boolean to BigInt\/field\/group one and zero\ntemplate \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 \nstd::size_t sizeBits(const snarklib::BigInt& dummy) {\n return snarklib::BigInt::maxBits();\n}\n\n\/\/ returns number of matching bits starting from most significant bit\ntemplate \nint matchMSB(const std::vector& a,\n const std::vector& 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 valueBits(const bool& a);\nstd::vector valueBits(const std::uint32_t& a);\nstd::vector valueBits(const std::uint64_t& a);\n\ntemplate \nstd::vector valueBits(const snarklib::BigInt& a) {\n std::vector 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 \nstd::vector bitsValue(UINT_N& a, const std::vector& 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 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& v);\n\n\/\/ overflow addition (uint32_t and uint64_t)\ntemplate \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\nUSE_ASSERT#ifndef _SNARKFRONT_POWERS_OF_2_HPP_\n#define _SNARKFRONT_POWERS_OF_2_HPP_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \/\/ snarklib\n\nnamespace snarkfront {\n\n\/\/ look up table for powers of 2 for BigInt\/field\/group\ntemplate \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& 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 m_lut; \/\/ index -> T(2^index)\n};\n\n\/\/ convert Boolean to BigInt\/field\/group one and zero\ntemplate \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 \nstd::size_t sizeBits(const snarklib::BigInt& dummy) {\n return snarklib::BigInt::maxBits();\n}\n\n\/\/ returns number of matching bits starting from most significant bit\ntemplate \nint matchMSB(const std::vector& a,\n const std::vector& 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 valueBits(const bool& a);\nstd::vector valueBits(const std::uint32_t& a);\nstd::vector valueBits(const std::uint64_t& a);\n\ntemplate \nstd::vector valueBits(const snarklib::BigInt& a) {\n std::vector 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 \nstd::vector bitsValue(UINT_N& a, const std::vector& 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 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& v);\n\n\/\/ overflow addition (uint32_t and uint64_t)\ntemplate \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":"#include \n#include \n#include \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;inext;\n\t\n\treturn ¤tNode->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;inext;\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;inext;\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;iget(i) << \" \";\n\tcout<= 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}\nnow includes multiples below indecated#include \n#include \n#include \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;inext;\n\t\n\treturn ¤tNode->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;inext;\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;inext;\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;iget(i) << \" \";\n\tcout<= 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":"\/*\r\n * Copyright (c) 2015-2016 Alex Spataru \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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Windows hacks\r\n\/\/------------------------------------------------------------------------------\r\n\r\n#if defined Q_OS_WIN\r\n #include \r\n #include \r\n #include \r\n #include \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 \r\n #include \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 (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 (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 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\nFixed Linux CPU usage GUI update\/*\r\n * Copyright (c) 2015-2016 Alex Spataru \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 \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/\/------------------------------------------------------------------------------\r\n\/\/ Windows hacks\r\n\/\/------------------------------------------------------------------------------\r\n\r\n#if defined Q_OS_WIN\r\n #include \r\n #include \r\n #include \r\n #include \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 \r\n #include \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 (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 (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 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":"\/* 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 \n#include \n#include \n#include \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 writer(buffer);\n rapidjson::PrettyWriter 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}\nRun clang-format\/* 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 \n#include \n#include \n#include \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 writer(buffer);\n rapidjson::PrettyWriter 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":"\/**\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 \n#include \n#include \n#include \n\nnamespace detail {\ntemplate ::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 ::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::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 ::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\nUpdate merge_sort.hpp\/**\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 \n#include \n#include \n#include \n\nnamespace detail {\ntemplate ::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 ::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::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 ::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":"#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 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 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 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(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\nexposed more wedge configurations for FRawMesh#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 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 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 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(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 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 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 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 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":"#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace mtl {\n\nnamespace internal {\n static constexpr std::size_t Max = std::numeric_limits::max();\n\n template struct index_of_type;\n template\n struct index_of_type> {\n static constexpr auto value = Max;\n };\n template\n struct index_of_type> {\n static constexpr auto value = 0;\n };\n template\n struct index_of_type> {\n static constexpr auto next = index_of_type>::value;\n static constexpr auto value = next == Max ? Max : next + 1;\n };\n\n template \n struct has_type {\n static constexpr auto value = internal::index_of_type::value != internal::Max;\n };\n\n template struct ConcatImpl;\n template\n struct ConcatImpl, std::tuple> {\n using type = std::tuple;\n };\n template\n struct ConcatImpl, std::tuple, Tuples...> {\n using type = typename ConcatImpl, Tuples...>::type;\n };\n\n template struct TailImpl;\n template<> struct TailImpl> { using type = std::tuple<>; };\n template\n struct TailImpl> {\n using type = std::tuple;\n };\n\n template class Operation> struct TransformImpl;\n template class Operation, typename... Params>\n struct TransformImpl, Operation> {\n using type = std::tuple::type...>;\n };\n\n template class Predicate, typename Tuple, typename Result = std::tuple<>, typename Enable = void> struct FilterImpl;\n template class Predicate, typename... Done>\n struct FilterImpl, std::tuple> {\n using type = std::tuple;\n };\n template class Predicate, typename Head, typename... Tail, typename... Done>\n struct FilterImpl, std::tuple,\n typename std::enable_if::value>::type> {\n using type = typename FilterImpl, std::tuple>::type;\n };\n template class Predicate, typename Head, typename... Tail, typename... Done>\n struct FilterImpl, std::tuple,\n typename std::enable_if::value>::type> {\n using type = typename FilterImpl, std::tuple>::type;\n };\n\n template, typename Enabled = void> struct UniqueImpl;\n template\n struct UniqueImpl, std::tuple> {\n using type = std::tuple;\n };\n template\n struct UniqueImpl, std::tuple,\n typename std::enable_if>::value>::type> {\n using type = typename UniqueImpl, std::tuple>::type;\n };\n template\n struct UniqueImpl, std::tuple,\n typename std::enable_if>::value>::type> {\n using type = typename UniqueImpl, std::tuple>::type;\n };\n\n template\n struct WithoutFilter {\n template\n struct Predicate {\n static constexpr auto value = !std::is_same::value;\n };\n };\n template struct WithoutImpl;\n template\n struct WithoutImpl> {\n using type = typename FilterImpl::template Predicate, std::tuple, std::tuple<>>::type;\n };\n\n template> struct InterleaveImpl;\n template\n struct InterleaveImpl, std::tuple<>, std::tuple> {\n using type = std::tuple;\n };\n template\n struct InterleaveImpl, std::tuple<>, std::tuple> {\n using type = std::tuple;\n };\n template\n struct InterleaveImpl, std::tuple, std::tuple> {\n using type = std::tuple;\n };\n template\n struct InterleaveImpl, std::tuple, std::tuple> {\n using type = typename InterleaveImpl, std::tuple, std::tuple>::type;\n };\n\n template\n struct LessOrSame {\n static constexpr auto value = index_of_type::value <= index_of_type::value;\n };\n\n template, typename Enabled = void> struct MergeImpl {};\n template\n struct MergeImpl, std::tuple, Comp, std::tuple> {\n using type = std::tuple;\n };\n template\n struct MergeImpl, std::tuple<>, Comp, std::tuple> {\n using type = std::tuple;\n };\n template\n struct MergeImpl, std::tuple, Comp, std::tuple,\n typename std::enable_if::value>::type> {\n using type = typename MergeImpl, std::tuple, Comp, std::tuple>::type;\n };\n template\n struct MergeImpl, std::tuple, Comp, std::tuple,\n typename std::enable_if::value>::type> {\n using type = typename MergeImpl, std::tuple, Comp, std::tuple>::type;\n };\n\n template, typename Right = std::tuple<>, typename Enabled = void> struct PartitionImpl;\n template\n struct PartitionImpl, Pivot, Comp, std::tuple, std::tuple> {\n using left = std::tuple;\n using right = std::tuple;\n };\n template\n struct PartitionImpl, Pivot, Comp, std::tuple, std::tuple,\n typename std::enable_if::value>::type> {\n using left = typename PartitionImpl, Pivot, Comp, std::tuple, std::tuple>::left;\n using right = typename PartitionImpl, Pivot, Comp, std::tuple, std::tuple>::right;\n };\n template\n struct PartitionImpl, Pivot, Comp, std::tuple, std::tuple,\n typename std::enable_if::value>::type> {\n using left = typename PartitionImpl, Pivot, Comp, std::tuple, std::tuple>::left;\n using right = typename PartitionImpl, Pivot, Comp, std::tuple, std::tuple>::right;\n };\n\n template struct SortImpl;\n template struct SortImpl, Comparison> { using type = std::tuple<>; };\n template struct SortImpl, Comparison> { using type = std::tuple; };\n template\n struct SortImpl, Comparison> {\n using partition = PartitionImpl, Head, Comparison>;\n using sorted_left = typename SortImpl::type;\n using sorted_right = typename SortImpl::type;\n using type = typename ConcatImpl, sorted_right>::type;\n };\n\n} \/\/ namespace internal\n\ntemplate using has_type = typename internal::has_type;\ntemplate using select = std::tuple::type...>;\ntemplate using head = typename std::tuple_element<0, Tuple>::type;\ntemplate using tail = typename internal::TailImpl::type;\ntemplate using concat = typename internal::ConcatImpl, Tuples...>::type;\ntemplate class Operation> using transform = typename internal::TransformImpl::type;\ntemplate class Predicate, typename Tuple> using filter = typename internal::FilterImpl::type;\ntemplate using unique = typename internal::UniqueImpl::type;\ntemplate using without = typename internal::WithoutImpl::type;\ntemplate using interleave = typename internal::InterleaveImpl::type;\ntemplate using merge = typename internal::MergeImpl>::type;\ntemplate using partition = typename internal::PartitionImpl::type;\ntemplate using sort = typename internal::SortImpl::type;\n\n} \/\/ namespace mtl\nindex_of#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace mtl {\n\nnamespace internal {\n static constexpr std::size_t Max = std::numeric_limits::max();\n\n template struct index_of_type;\n template\n struct index_of_type> {\n static constexpr auto value = Max;\n };\n template\n struct index_of_type> {\n static constexpr auto value = 0;\n };\n template\n struct index_of_type> {\n static constexpr auto next = index_of_type>::value;\n static constexpr auto value = next == Max ? Max : next + 1;\n };\n\n template \n struct has_type {\n static constexpr auto value = internal::index_of_type::value != internal::Max;\n };\n\n template struct ConcatImpl;\n template\n struct ConcatImpl, std::tuple> {\n using type = std::tuple;\n };\n template\n struct ConcatImpl, std::tuple, Tuples...> {\n using type = typename ConcatImpl, Tuples...>::type;\n };\n\n template struct TailImpl;\n template<> struct TailImpl> { using type = std::tuple<>; };\n template\n struct TailImpl> {\n using type = std::tuple;\n };\n\n template class Operation> struct TransformImpl;\n template class Operation, typename... Params>\n struct TransformImpl, Operation> {\n using type = std::tuple::type...>;\n };\n\n template class Predicate, typename Tuple, typename Result = std::tuple<>, typename Enable = void> struct FilterImpl;\n template class Predicate, typename... Done>\n struct FilterImpl, std::tuple> {\n using type = std::tuple;\n };\n template class Predicate, typename Head, typename... Tail, typename... Done>\n struct FilterImpl, std::tuple,\n typename std::enable_if::value>::type> {\n using type = typename FilterImpl, std::tuple>::type;\n };\n template class Predicate, typename Head, typename... Tail, typename... Done>\n struct FilterImpl, std::tuple,\n typename std::enable_if::value>::type> {\n using type = typename FilterImpl, std::tuple>::type;\n };\n\n template, typename Enabled = void> struct UniqueImpl;\n template\n struct UniqueImpl, std::tuple> {\n using type = std::tuple;\n };\n template\n struct UniqueImpl, std::tuple,\n typename std::enable_if>::value>::type> {\n using type = typename UniqueImpl, std::tuple>::type;\n };\n template\n struct UniqueImpl, std::tuple,\n typename std::enable_if>::value>::type> {\n using type = typename UniqueImpl, std::tuple>::type;\n };\n\n template\n struct WithoutFilter {\n template\n struct Predicate {\n static constexpr auto value = !std::is_same::value;\n };\n };\n template struct WithoutImpl;\n template\n struct WithoutImpl> {\n using type = typename FilterImpl::template Predicate, std::tuple, std::tuple<>>::type;\n };\n\n template> struct InterleaveImpl;\n template\n struct InterleaveImpl, std::tuple<>, std::tuple> {\n using type = std::tuple;\n };\n template\n struct InterleaveImpl, std::tuple<>, std::tuple> {\n using type = std::tuple;\n };\n template\n struct InterleaveImpl, std::tuple, std::tuple> {\n using type = std::tuple;\n };\n template\n struct InterleaveImpl, std::tuple, std::tuple> {\n using type = typename InterleaveImpl, std::tuple, std::tuple>::type;\n };\n\n template\n struct LessOrSame {\n static constexpr auto value = index_of_type::value <= index_of_type::value;\n };\n\n template, typename Enabled = void> struct MergeImpl {};\n template\n struct MergeImpl, std::tuple, Comp, std::tuple> {\n using type = std::tuple;\n };\n template\n struct MergeImpl, std::tuple<>, Comp, std::tuple> {\n using type = std::tuple;\n };\n template\n struct MergeImpl, std::tuple, Comp, std::tuple,\n typename std::enable_if::value>::type> {\n using type = typename MergeImpl, std::tuple, Comp, std::tuple>::type;\n };\n template\n struct MergeImpl, std::tuple, Comp, std::tuple,\n typename std::enable_if::value>::type> {\n using type = typename MergeImpl, std::tuple, Comp, std::tuple>::type;\n };\n\n template, typename Right = std::tuple<>, typename Enabled = void> struct PartitionImpl;\n template\n struct PartitionImpl, Pivot, Comp, std::tuple, std::tuple> {\n using left = std::tuple;\n using right = std::tuple;\n };\n template\n struct PartitionImpl, Pivot, Comp, std::tuple, std::tuple,\n typename std::enable_if::value>::type> {\n using left = typename PartitionImpl, Pivot, Comp, std::tuple, std::tuple>::left;\n using right = typename PartitionImpl, Pivot, Comp, std::tuple, std::tuple>::right;\n };\n template\n struct PartitionImpl, Pivot, Comp, std::tuple, std::tuple,\n typename std::enable_if::value>::type> {\n using left = typename PartitionImpl, Pivot, Comp, std::tuple, std::tuple>::left;\n using right = typename PartitionImpl, Pivot, Comp, std::tuple, std::tuple>::right;\n };\n\n template struct SortImpl;\n template struct SortImpl, Comparison> { using type = std::tuple<>; };\n template struct SortImpl, Comparison> { using type = std::tuple; };\n template\n struct SortImpl, Comparison> {\n using partition = PartitionImpl, Head, Comparison>;\n using sorted_left = typename SortImpl::type;\n using sorted_right = typename SortImpl::type;\n using type = typename ConcatImpl, sorted_right>::type;\n };\n\n} \/\/ namespace internal\n\ntemplate using has_type = typename internal::has_type;\ntemplate using select = std::tuple::type...>;\ntemplate using head = typename std::tuple_element<0, Tuple>::type;\ntemplate using tail = typename internal::TailImpl::type;\ntemplate using concat = typename internal::ConcatImpl, Tuples...>::type;\ntemplate class Operation> using transform = typename internal::TransformImpl::type;\ntemplate class Predicate, typename Tuple> using filter = typename internal::FilterImpl::type;\ntemplate using unique = typename internal::UniqueImpl::type;\ntemplate using without = typename internal::WithoutImpl::type;\ntemplate using interleave = typename internal::InterleaveImpl::type;\ntemplate using merge = typename internal::MergeImpl>::type;\ntemplate using partition = typename internal::PartitionImpl::type;\ntemplate using sort = typename internal::SortImpl::type;\ntemplate constexpr auto index_of = internal::index_of_type, std::tuple...>>::value;\n\n} \/\/ namespace mtl\n<|endoftext|>"} {"text":"#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 \r\n#else\r\n#include \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\nasdgasdg#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 \r\n#else\r\n#include \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":"#include \n#include \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}\nShortened to long line.#include \n#include \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":"\/**\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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 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 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 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 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 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 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 interpreter) {\n Command::execute(expression, runtime, out, interpreter);\n UNUSED(interpreter);\n\n vector 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 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 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 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 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}\nBug fix: Nested failing if's were causing outer else's to be called\/**\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 \n#include \n#include \n#include \n#include \n#include \n#include \n#include \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 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 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 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 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 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 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 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 interpreter) {\n Command::execute(expression, runtime, out, interpreter);\n UNUSED(interpreter);\n\n vector 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 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 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 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 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":"#include \"vexporter.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef QT_NO_PRINTER\n#include \n#include \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 %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[fix] show the default filename in 'Export As' dialog (#35)#include \"vexporter.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef QT_NO_PRINTER\n#include \n#include \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 %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":"\/\/ 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 \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 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 physicsRepresentation;\n\tphysicsRepresentation = std::make_shared(name + \" Physics\");\n\tphysicsRepresentation->setIntegrationScheme(integrationScheme);\n\tphysicsRepresentation->setRayleighDampingMass(1e-2);\n\tphysicsRepresentation->setRayleighDampingStiffness(1e-3);\n\n\tstd::array 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, 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 boundaryConditionsNodeIdx = {{0, 1}};\n\n\tstd::shared_ptr initialState = std::make_shared();\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 element = std::make_shared(*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 graphicsRepresentation;\n\tgraphicsRepresentation = std::make_shared(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 femSceneElement = std::make_shared(name);\n\tfemSceneElement->addComponent(physicsRepresentation);\n\tfemSceneElement->addComponent(graphicsRepresentation);\n\n\tauto physicsToGraphics =\n\t\tstd::make_shared(\"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\nFix typo in UnitTest name\/\/ 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 \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 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 physicsRepresentation;\n\tphysicsRepresentation = std::make_shared(name + \" Physics\");\n\tphysicsRepresentation->setIntegrationScheme(integrationScheme);\n\tphysicsRepresentation->setRayleighDampingMass(1e-2);\n\tphysicsRepresentation->setRayleighDampingStiffness(1e-3);\n\n\tstd::array 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, 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 boundaryConditionsNodeIdx = {{0, 1}};\n\n\tstd::shared_ptr initialState = std::make_shared();\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 element = std::make_shared(*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 graphicsRepresentation;\n\tgraphicsRepresentation = std::make_shared(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 femSceneElement = std::make_shared(name);\n\tfemSceneElement->addComponent(physicsRepresentation);\n\tfemSceneElement->addComponent(graphicsRepresentation);\n\n\tauto physicsToGraphics =\n\t\tstd::make_shared(\"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":"\/*\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 \n#include \n#include \n\n#ifdef __WXOSX__\n\n@interface LanguagesDataSource : NSObject\n@property const wxArrayString *data;\n@property NSArray* 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 *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\nFix language control not having initial value w\/ GTK+\/*\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 \n#include \n#include \n\n#ifdef __WXOSX__\n\n@interface LanguagesDataSource : NSObject\n@property const wxArrayString *data;\n@property NSArray* 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 *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":"\/*\n * Author: Mihai T Panu \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 \n#include \n#include \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}\nrobotics: added full implementation for demo\/*\n * Author: Mihai T Panu \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 \n#include \n#include \n#include \n#include \n#include \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 \n \/\/ Except for the 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":"\/*\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 \n#include \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(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(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(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(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(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(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(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\nAdd timestamp conversion in cass_uuid_min\/max_from_time() function to be consistent with cass_uuid_gen_from_time() function. CPP-283\/*\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 \n#include \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(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(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(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(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(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(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(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":"\/* -*- 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 \n#include \n#include \n#include \n#include \n\n#include \n\n#ifdef __GNUC__\n# include \n#endif\n\n#include \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