text
stringlengths
54
60.6k
<commit_before>630b5a38-2e4e-11e5-9284-b827eb9e62be<commit_msg>63106550-2e4e-11e5-9284-b827eb9e62be<commit_after>63106550-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>6ee5783e-2e4e-11e5-9284-b827eb9e62be<commit_msg>6eea6e66-2e4e-11e5-9284-b827eb9e62be<commit_after>6eea6e66-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/** * @file edge.cpp * @brief Simple test for OpenCV * @author Denis Deryugin <deryugin.denis@gmail.com> * @version * @date 03.06.2019 */ #include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <stdio.h> #include <drivers/video/fb.h> using namespace cv; using namespace std; static void help() { printf("\nThis sample demonstrates Canny edge detection\n" "Call:\n" " ./edge [threshold]\n\n"); } static const char* keys = { "{help h||}{@repeat |1 | number}" }; int main(int argc, const char** argv) { int edgeThresh = 2; Mat image, gray, edge, cedge; struct fb_info *fbi = fb_lookup(0); CommandLineParser parser(argc, argv, keys); if (parser.has("help")) { help(); return 0; } edgeThresh = parser.get<int>(0); string filename = "fruits.png"; image = imread(filename, 1); if(image.empty()) { printf("Cannot read image file: %s\n", filename.c_str()); help(); return -1; } cedge.create(image.size(), image.type()); cvtColor(image, gray, COLOR_BGR2GRAY); blur(gray, edge, Size(3,3)); Canny(edge, edge, edgeThresh, edgeThresh*3, 3); cedge = Scalar::all(0); image.copyTo(cedge, edge); printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel); printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh); for (int i = 0; i < cedge.cols; i++) { for (int j = 0; j < cedge.rows; j++) { Vec3b intensity = cedge.at<Vec3b>(j, i); unsigned rgb888 = 0xFF000000 | intensity.val[0] | ((intensity.val[1]) << 8) | ((intensity.val[2]) << 16); ((uint32_t *) fbi->screen_base)[fbi->var.xres * j + i] = rgb888; } } return 0; } <commit_msg>edges: Pass image as a parameter<commit_after>/** * @file edge.cpp * @brief Simple test for OpenCV * @author Denis Deryugin <deryugin.denis@gmail.com> * @version * @date 03.06.2019 */ #include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <stdio.h> #include <drivers/video/fb.h> using namespace cv; using namespace std; static void help(void) { printf("\nThis sample demonstrates Canny edge detection\n" "Call:\n" " ./edge [image [threshold]] \n\n"); } static const char* keys = { "{help h||}" "{@image | \"fruits.png\" | source image }" "{@repeat |1 | number}" }; int main(int argc, const char** argv) { int edgeThresh = 2; Mat image, gray, edge, cedge; struct fb_info *fbi = fb_lookup(0); CommandLineParser parser(argc, argv, keys); if (parser.has("help")) { help(); return 0; } edgeThresh = parser.get<int>(1); string filename = parser.get<String>("@image"); image = imread(filename, 1); if(image.empty()) { printf("Cannot read image file: %s\n", filename.c_str()); help(); return -1; } cedge.create(image.size(), image.type()); cvtColor(image, gray, COLOR_BGR2GRAY); blur(gray, edge, Size(3,3)); Canny(edge, edge, edgeThresh, edgeThresh*3, 3); cedge = Scalar::all(0); image.copyTo(cedge, edge); printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel); printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh); for (int i = 0; i < cedge.cols; i++) { for (int j = 0; j < cedge.rows; j++) { Vec3b intensity = cedge.at<Vec3b>(j, i); unsigned rgb888 = 0xFF000000 | intensity.val[0] | ((intensity.val[1]) << 8) | ((intensity.val[2]) << 16); ((uint32_t *) fbi->screen_base)[fbi->var.xres * j + i] = rgb888; } } return 0; } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <tuple> // template <class... Types> class tuple; // template <class... Types> // class tuple_size<tuple<Types...>> // : public integral_constant<size_t, sizeof...(Types)> { }; // UNSUPPORTED: c++98, c++03 #include <tuple> #include <array> #include <type_traits> struct Dummy1 {}; struct Dummy2 {}; struct Dummy3 {}; template <> class std::tuple_size<Dummy1> { public: static size_t value; }; template <> class std::tuple_size<Dummy2> { public: static void value() {} }; template <> class std::tuple_size<Dummy3> {}; int main() { // Test that tuple_size<const T> is not incomplete when tuple_size<T>::value // is well-formed but not a constant expression. { // expected-error@__tuple:* 1 {{is not a constant expression}} (void)std::tuple_size<const Dummy1>::value; // expected-note {{here}} } // Test that tuple_size<const T> is not incomplete when tuple_size<T>::value // is well-formed but not convertible to size_t. { // expected-error@__tuple:* 1 {{value of type 'void ()' is not implicitly convertible to 'unsigned long'}} (void)std::tuple_size<const Dummy2>::value; // expected-note {{here}} } // Test that tuple_size<const T> generates an error when tuple_size<T> is // complete but ::value isn't a constant expression convertible to size_t. { // expected-error@__tuple:* 1 {{no member named 'value'}} (void)std::tuple_size<const Dummy3>::value; // expected-note {{here}} } } <commit_msg>Fix verify test on 32 bit systems<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <tuple> // template <class... Types> class tuple; // template <class... Types> // class tuple_size<tuple<Types...>> // : public integral_constant<size_t, sizeof...(Types)> { }; // UNSUPPORTED: c++98, c++03 #include <tuple> #include <array> #include <type_traits> struct Dummy1 {}; struct Dummy2 {}; struct Dummy3 {}; template <> class std::tuple_size<Dummy1> { public: static size_t value; }; template <> class std::tuple_size<Dummy2> { public: static void value() {} }; template <> class std::tuple_size<Dummy3> {}; int main() { // Test that tuple_size<const T> is not incomplete when tuple_size<T>::value // is well-formed but not a constant expression. { // expected-error@__tuple:* 1 {{is not a constant expression}} (void)std::tuple_size<const Dummy1>::value; // expected-note {{here}} } // Test that tuple_size<const T> is not incomplete when tuple_size<T>::value // is well-formed but not convertible to size_t. { // expected-error@__tuple:* 1 {{value of type 'void ()' is not implicitly convertible to}} (void)std::tuple_size<const Dummy2>::value; // expected-note {{here}} } // Test that tuple_size<const T> generates an error when tuple_size<T> is // complete but ::value isn't a constant expression convertible to size_t. { // expected-error@__tuple:* 1 {{no member named 'value'}} (void)std::tuple_size<const Dummy3>::value; // expected-note {{here}} } } <|endoftext|>
<commit_before>ec8f585e-2e4e-11e5-9284-b827eb9e62be<commit_msg>ec9456ce-2e4e-11e5-9284-b827eb9e62be<commit_after>ec9456ce-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/** * @file edge.cpp * @brief Simple test for OpenCV * @author Denis Deryugin <deryugin.denis@gmail.com> * @version * @date 03.06.2019 */ #include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <stdio.h> #include <drivers/video/fb.h> using namespace cv; using namespace std; static void help(void) { printf("\nThis sample demonstrates Canny edge detection\n" "Call:\n" " ./edge [image [threshold]] \n\n"); } static const char* keys = { "{help h||}" "{@image | \"fruits.png\" | source image }" "{@repeat |1 | number}" }; int main(int argc, const char** argv) { int edgeThresh = 2; Mat image, gray, edge, cedge; struct fb_info *fbi = fb_lookup(0); CommandLineParser parser(argc, argv, keys); if (parser.has("help")) { help(); return 0; } edgeThresh = parser.get<int>(1); string filename = parser.get<String>("@image"); image = imread(filename, 1); if(image.empty()) { printf("Cannot read image file: %s\n", filename.c_str()); help(); return -1; } cedge.create(image.size(), image.type()); cvtColor(image, gray, COLOR_BGR2GRAY); blur(gray, edge, Size(3,3)); Canny(edge, edge, edgeThresh, edgeThresh*3, 3); cedge = Scalar::all(0); image.copyTo(cedge, edge); printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel); printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh); for (int x = 0; x < cedge.cols; x++) { for (int y = 0; y < cedge.rows; y++) { Vec3b intensity = cedge.at<Vec3b>(y, x); unsigned rgb888 = 0xFF000000 | intensity.val[0] | ((intensity.val[1]) << 8) | ((intensity.val[2]) << 16); ((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x] = rgb888; } } return 0; } <commit_msg>reordered iteration over Y/X dimensions of image for better cache usage<commit_after>/** * @file edge.cpp * @brief Simple test for OpenCV * @author Denis Deryugin <deryugin.denis@gmail.com> * @version * @date 03.06.2019 */ #include "opencv2/core/utility.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <stdio.h> #include <drivers/video/fb.h> using namespace cv; using namespace std; static void help(void) { printf("\nThis sample demonstrates Canny edge detection\n" "Call:\n" " ./edge [image [threshold]] \n\n"); } static const char* keys = { "{help h||}" "{@image | \"fruits.png\" | source image }" "{@repeat |1 | number}" }; int main(int argc, const char** argv) { int edgeThresh = 2; Mat image, gray, edge, cedge; struct fb_info *fbi = fb_lookup(0); CommandLineParser parser(argc, argv, keys); if (parser.has("help")) { help(); return 0; } edgeThresh = parser.get<int>(1); string filename = parser.get<String>("@image"); image = imread(filename, 1); if(image.empty()) { printf("Cannot read image file: %s\n", filename.c_str()); help(); return -1; } cedge.create(image.size(), image.type()); cvtColor(image, gray, COLOR_BGR2GRAY); blur(gray, edge, Size(3,3)); Canny(edge, edge, edgeThresh, edgeThresh*3, 3); cedge = Scalar::all(0); image.copyTo(cedge, edge); printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel); printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh); for (int y = 0; y < cedge.rows; y++) { for (int x = 0; x < cedge.cols; x++) { Vec3b intensity = cedge.at<Vec3b>(y, x); unsigned rgb888 = 0xFF000000 | intensity.val[0] | ((intensity.val[1]) << 8) | ((intensity.val[2]) << 16); ((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x] = rgb888; } } return 0; } <|endoftext|>
<commit_before>3cfc4b32-2e4d-11e5-9284-b827eb9e62be<commit_msg>3d015258-2e4d-11e5-9284-b827eb9e62be<commit_after>3d015258-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include <iostream> #include <string> #include <cstdio> #include <stdexcept> #include "parse.h" #include "API.hpp" #include "CatalogManager.hpp" #include "IndexManager.hpp" #include "RecordManager.hpp" #include "BufferManager.hpp" using namespace std; void printList (const Entries& rlist, const TableDefinition& tdef); int main() { char dmnb[] = " _ __ __ _ _ _ \n" " __| | | \\/ | | \\| | | |__ \n" " / _` | | |\\/| | | .` | | '_ \\ \n" " \\__,_| |_|__|_| |_|\\_| |_.__/ \n" " _|\"\"\"\"\"|_|\"\"\"\"\"|_|\"\"\"\"\"|_|\"\"\"\"\"| \n" " \"`-0-0-'\"`-0-0-'\"`-0-0-'\"`-0-0-' \n" ; char sepr[] = " ---------------------------------\n" ; char fail[] = " ___ _____ ____\n" " / _ \\_ _|_ /\n" " | (_) || | / / \n" " \\___/ |_| /___|\n" " init failed :( \n" ; char byee[] = " BBBByyyyeeee ~~~~\n" ; char welcm[] = " Welcome to DminiB system(exclaimation),\n" " enter command below\n" ; cout << dmnb << sepr; try { BufferManager bufferManager; CatalogManager catlogManager; RecordManager recordManager(bufferManager); IndexManager indexManager(bufferManager); API api(catlogManager, recordManager, indexManager); cout << welcm << endl; string str, temp; do { str.clear(); temp.clear(); if (!cin) { cout << endl; break; } // check if ^D cout << "dMNb> "; do { getline(cin, temp); str += " " + temp; } while (temp.find(';') == string::npos && cin); if (str == " exit;" || str == " exit") break; if (str == " " ) break; PlanList& plist = parse(str); // call api according to plist for (PlanList::iterator plan = plist.begin(); plan != plist.end(); ++plan) { std::string tname = plan->tname; // seperate function call accoring to acti Action acti = plan->acti; WrapperList &wlist = plan->wlist; try { switch(acti) { case DELV: if ( !wlist.size() ) { cout << "del item num: " << api.remove(tname) << endl; } else { cout << "del item num: " << api.remove(tname, wlist) << endl; } break; case SELV: if ( !wlist.size() ) { const Entries rlist = api.select(tname); printList(rlist, catlogManager.getTableDef(tname)); } else { const Entries rlist = api.select(tname, wlist); printList(rlist, catlogManager.getTableDef(tname)); } break; case CTBL: api.createTable(tname, wlist); break; case DTBL: api.dropTable(tname); break; case CIDX: api.createIndex(tname, wlist.begin()->name, wlist.begin()->strv); break; case INSV: //cout << "[main] api.insertEntry calling..." << endl; cout.flush(); api.insertEntry(tname, wlist); break; case DIDX: api.dropIndex(tname); break; default: cerr << "unhandled action\n"; break; } } catch (exception const& e) { cerr << "err: " << e.what() << endl; } //cout << str << endl; /* for (WrapperList::const_iterator j = plan->wlist.begin(); j != plan->wlist.end(); j++) j->debug(); */ } } while (1); } catch (exception const& e) { cerr << "err: " << e.what() << endl; return(-1); } catch (...) { cout << fail << endl; return(-1); } cout << byee; return 0; } void printList (const Entries& rlist, const TableDefinition& tdef) { if ( rlist.size() ) { for (TableDefinition::const_iterator i = tdef.begin(); i != tdef.end(); i++) { //if ( i->type == utls::CHAR) cout.width(i->intv); //else cout.width(10); cout << i->name << " "; } cout << endl; } for (Entries::const_iterator i = rlist.begin(); i != rlist.end(); i++) { for (Entry::const_iterator j = i->begin(); j != i->end(); j++) { j->debug(); } cout << endl; } cout << rlist.size() << " rows selected" << endl; } <commit_msg>mod: ....<commit_after>#include <iostream> #include <string> #include <cstdio> #include <stdexcept> #include "parse.h" #include "API.hpp" #include "CatalogManager.hpp" #include "IndexManager.hpp" #include "RecordManager.hpp" #include "BufferManager.hpp" using namespace std; void printList (const Entries& rlist, const TableDefinition& tdef); int main() { char dmnb[] = " _ __ __ _ _ _ \n" " __| | | \\/ | | \\| | | |__ \n" " / _` | | |\\/| | | .` | | '_ \\ \n" " \\__,_| |_|__|_| |_|\\_| |_.__/ \n" " _|\"\"\"\"\"|_|\"\"\"\"\"|_|\"\"\"\"\"|_|\"\"\"\"\"| \n" " \"`-0-0-'\"`-0-0-'\"`-0-0-'\"`-0-0-' \n" ; char sepr[] = " ---------------------------------\n" ; char fail[] = " ___ _____ ____\n" " / _ \\_ _|_ /\n" " | (_) || | / / \n" " \\___/ |_| /___|\n" " init failed :( \n" ; char byee[] = " BBBByyyyeeee ~~~~\n" ; char welcm[] = " Welcome to DminiB system(exclaimation),\n" " enter command below\n" ; cout << dmnb << sepr; try { BufferManager bufferManager; CatalogManager catlogManager; RecordManager recordManager(bufferManager); IndexManager indexManager(bufferManager); API api(catlogManager, recordManager, indexManager); cout << welcm << endl; string str, temp; do { str.clear(); temp.clear(); if (!cin) { cout << endl; break; } // check if ^D cout << "dMNb> "; do { getline(cin, temp); str += " " + temp; } while (temp.find(';') == string::npos && cin); if (str == " exit;" || str == " exit") break; if (str == " " ) break; if ( str.substr(0, 4) == "exec" ) { str.erase(0, 5); str.erase(str.length() -1, 1); cout << str; break; } PlanList& plist = parse(str); // call api according to plist for (PlanList::iterator plan = plist.begin(); plan != plist.end(); ++plan) { std::string tname = plan->tname; // seperate function call accoring to acti Action acti = plan->acti; WrapperList &wlist = plan->wlist; try { switch(acti) { case DELV: if ( !wlist.size() ) { cout << "del item num: " << api.remove(tname) << endl; } else { cout << "del item num: " << api.remove(tname, wlist) << endl; } break; case SELV: if ( !wlist.size() ) { const Entries rlist = api.select(tname); printList(rlist, catlogManager.getTableDef(tname)); } else { const Entries rlist = api.select(tname, wlist); printList(rlist, catlogManager.getTableDef(tname)); } break; case CTBL: api.createTable(tname, wlist); break; case DTBL: api.dropTable(tname); break; case CIDX: api.createIndex(tname, wlist.begin()->name, wlist.begin()->strv); break; case INSV: //cout << "[main] api.insertEntry calling..." << endl; cout.flush(); api.insertEntry(tname, wlist); break; case DIDX: api.dropIndex(tname); break; default: cerr << "unhandled action\n"; break; } } catch (exception const& e) { cerr << "err: " << e.what() << endl; } //cout << str << endl; /* for (WrapperList::const_iterator j = plan->wlist.begin(); j != plan->wlist.end(); j++) j->debug(); */ } } while (1); } catch (exception const& e) { cerr << "err: " << e.what() << endl; return(-1); } catch (...) { cout << fail << endl; return(-1); } cout << byee; return 0; } void printList (const Entries& rlist, const TableDefinition& tdef) { if ( rlist.size() ) { for (TableDefinition::const_iterator i = tdef.begin(); i != tdef.end(); i++) { //if ( i->type == utls::CHAR) cout.width(i->intv); //else cout.width(10); cout << i->name << " "; } cout << endl; } for (Entries::const_iterator i = rlist.begin(); i != rlist.end(); i++) { for (Entry::const_iterator j = i->begin(); j != i->end(); j++) { j->debug(); } cout << endl; } cout << rlist.size() << " rows selected" << endl; } <|endoftext|>
<commit_before>623f680c-2e4d-11e5-9284-b827eb9e62be<commit_msg>62447158-2e4d-11e5-9284-b827eb9e62be<commit_after>62447158-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>d1741dfe-2e4c-11e5-9284-b827eb9e62be<commit_msg>d1794374-2e4c-11e5-9284-b827eb9e62be<commit_after>d1794374-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>50b62c6a-2e4d-11e5-9284-b827eb9e62be<commit_msg>50bb38d6-2e4d-11e5-9284-b827eb9e62be<commit_after>50bb38d6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include <iostream> #include <string.h> #include <lux/index.h> #include <lux/types.h> static void usage() { std::cout << "usage:" << std::endl; std::cout << " luxcmd init db" << std::endl; std::cout << " luxcmd put db id [attr=value]...." << std::endl; } static bool open_db(Lux::Engine engine, const char* path, Lux::db_flags_t oflags=Lux::DB_RDWR) { if (!engine.open(path, oflags)) { std::cerr << "opening engine failed - " << path << std::endl; return false; } return true; } static int init(Lux::Engine engine, const char* db, int argc, char* argv[]) { return open_db(engine, db, Lux::DB_CREAT) ? 0 : 1; } static int put(Lux::Engine engine, const char* db, int argc, char* argv[]) { if (!open_db(engine, db)) { return 1; } Lux::Indexer indexer(engine); Lux::Document doc(argv[0]); int i; for (i = 1; i < argc; i++) { char* pair = strdupa(argv[i]); char* pc = strchr(pair, '='); const char* val; if (pc != NULL) { *pc = '\0'; val = pc + 1; } else { val = &pair[strlen(pair)]; } const char* key = pair; doc.add(Lux::Field::create(key, val)); } indexer.add(doc); return 0; } int main(int argc, char* argv[]) { if (argc < 3) { usage(); return 1; } const char* db = argv[2]; Lux::Config::Document config; if (!Lux::DocumentConfigParser::parse(db, config)) { std::cerr << "parse failed - " << db << std::endl; return 1; } Lux::Engine engine(config); const char* cmd = argv[1]; if (strcmp(cmd, "init") == 0) { return init(engine, db, argc - 4, argv + 4); } if (strcmp(cmd, "put") == 0) { return put(engine, db, argc - 4, argv + 4); } return 0; } // vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4 <commit_msg>Implemented search command.<commit_after>#include <iostream> #include <string.h> #include <lux/index.h> #include <lux/search.h> #include <lux/types.h> static void usage() { std::cout << "usage:" << std::endl; std::cout << " luxcmd init db" << std::endl; std::cout << " luxcmd put db id [attr=value]...." << std::endl; std::cout << " luxcmd search db phrase" << std::endl; } static bool open_db(Lux::Engine engine, const char* path, Lux::db_flags_t oflags=Lux::DB_RDWR) { if (!engine.open(path, oflags)) { std::cerr << "opening engine failed - " << path << std::endl; return false; } return true; } static int init(Lux::Engine engine, const char* db, int argc, char* argv[]) { return open_db(engine, db, Lux::DB_CREAT) ? 0 : 1; } static void print_line() { std::cout << "--------------------------------" << std::endl; } static int search(Lux::Engine engine, int argc, char* argv[]) { Lux::SortCondition scond(Lux::SORT_SCORE, Lux::DESC); Lux::Paging paging(100); Lux::Condition cond(scond, paging); Lux::Searcher searcher(engine); Lux::ResultSet rs = searcher.search(argv[0], cond); std::cout << "total hits: " << rs.get_total_num() << std::endl; rs.init_iter(); while (rs.has_next()) { Lux::Result r = rs.get_next(); print_line(); std::cout << "[id] " << r.get_id() << std::endl; } return 0; } static int put(Lux::Engine engine, int argc, char* argv[]) { Lux::Indexer indexer(engine); Lux::Document doc(argv[0]); int i; for (i = 1; i < argc; i++) { char* pair = strdupa(argv[i]); char* pc = strchr(pair, '='); const char* val; if (pc != NULL) { *pc = '\0'; val = pc + 1; } else { val = &pair[strlen(pair)]; } const char* key = pair; doc.add(Lux::Field::create(key, val)); } indexer.add(doc); return 0; } int main(int argc, char* argv[]) { if (argc < 3) { usage(); return 1; } const char* db = argv[2]; Lux::Config::Document config; if (!Lux::DocumentConfigParser::parse(db, config)) { std::cerr << "parse failed - " << db << std::endl; return 1; } Lux::Engine engine(config); const char* cmd = argv[1]; if (strcmp(cmd, "init") == 0) { return init(engine, db, argc - 3, argv + 3); } if (!open_db(engine, db)) { return 1; } if (strcmp(cmd, "put") == 0) { return put(engine, argc - 3, argv + 3); } if (strcmp(cmd, "search") == 0) { return search(engine, argc - 3, argv + 3); } return 0; } // vim: tabstop=4 shiftwidth=4 expandtab softtabstop=4 <|endoftext|>
<commit_before>fbdb2de8-2e4d-11e5-9284-b827eb9e62be<commit_msg>fbe01e52-2e4d-11e5-9284-b827eb9e62be<commit_after>fbe01e52-2e4d-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#define GLM_FORCE_RADIANS #define PI 3.14159265358979 #include <GL/glew.h> #include <glfw3.h> #include <glm/glm.hpp> #include <iostream> #include <math.h> #include <stdio.h> #include <stdlib.h> #include "gfx/Renderer.hpp" #include "gfx/VertexArray.hpp" #include "gfx/SkyBox.hpp" #include "gfx/importer/ObjLoader.hpp" #include "gfx/lights/Light.hpp" #include "gfx/lights/PointLight.hpp" #include "gfx/lights/DirLight.hpp" #include "gfx/shader/SimpleShader.hpp" #include "input/Actions.hpp" #include "input/Input.hpp" #include "DebugUtils.h" glm::vec3 get_random_color() { auto r = ((rand() % 100)/100.0); auto g = ((rand() % 100)/100.0); auto b = ((rand() % 100)/100.0); return glm::normalize(glm::vec3{r, g, b}); } std::vector<std::pair<glm::vec3, glm::vec3>> rain; void draw_rain(Renderer* r) { static float speed = 0.5; //if((rand() % 100)/100.0 < 0.5) { //for(int i = 0; i < 5; i++) { { auto x = ((rand() % 100)/100.0) * 10.0f; auto y = 20; auto z = ((rand() % 100)/100.0) * 10.0f; glm::vec3 from = glm::vec3(x,y,z); glm::vec3 to = from + glm::vec3{5, -16, 5}; rain.push_back(std::make_pair(from, to)); } std::vector<std::pair<glm::vec3, glm::vec3>> new_rain; for(auto& rain_pos: rain) { auto& from = std::get<0>(rain_pos); auto& to = std::get<1>(rain_pos); auto dir = glm::normalize(to - from); from += dir * speed; to += dir * speed; if(from.y > 0) { new_rain.push_back(rain_pos); } } r->draw_lines(rain, {0.1, 0.1, 0.1}); rain = new_rain; } static void error_callback(int error, const char* description) { fputs(description, stderr); } float step = 0.01f; int selected_light = -1; static void scroll_callback(GLFWwindow* window, double x_offset, double y_offset) { step = fmax(0.01f, fmin(step * pow(1.5, y_offset), 5)); } void rotate_camera(Camera& camera) { camera.rotate(-Input::get_mouse_dx() / 100.0f, camera.up); camera.rotate(-Input::get_mouse_dy() / 100.0f, glm::cross(camera.up, camera.dir)); } const int width = 1024; const int height = 768; int main(int argc, char ** argv) { glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(width, height, "glHondo", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; GLenum err = glewInit(); //To discard error 1280 from glewInit(). glGetError(); if(GLEW_OK != err) std::cout << glewGetErrorString(err) << std::endl; { const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* version = glGetString(GL_VERSION); printf("Renderer: %s\n", renderer); printf("Version: %s\n", version); glfwSetCursorPosCallback(window, Input::cursor_pos_callback); glfwSetKeyCallback(window, Input::key_callback); glfwSetScrollCallback(window, scroll_callback); Input::set_active_window(window); } Renderer renderer(width, height); auto& camera = renderer.get_camera(); Input::on(Actions::Forward, [&]() { camera.move_forward(step); }); Input::on(Actions::Backward, [&]() { camera.move_forward(-step); }); Input::on(Actions::Left, [&]() { camera.move_right(-step); }); Input::on(Actions::Right, [&]() { camera.move_right(step); }); Input::on(Actions::Up, [&]() { camera.translate({0, step, 0}); }); Input::on(Actions::Down, [&]() { camera.translate({0, -step, 0}); }); Input::on(GLFW_KEY_Z, [&] { renderer.toggle_wireframe(); }); Input::on(GLFW_KEY_G, []() { Input::lock_mouse(); }); ObjLoader loader; //loader.preload_file("assets/sponza.obj"); loader.preload_file("assets/Cube.obj"); loader.preload_file("assets/Floor.obj"); loader.preload_file("assets/SkyDome16.obj"); std::cout << "Load files\n"; loader.load_files(); std::cout << "Loading files done\n"; Mesh skydome_mesh = loader.get_meshes("assets/SkyDome16.obj")[0]; Mesh cube_mesh = loader.get_meshes("assets/Cube.obj")[0]; Mesh floor_mesh = loader.get_meshes("assets/Floor.obj")[0]; //std::vector<Mesh> sponza_meshes = loader.get_meshes("assets/sponza.obj"); auto pl2 = std::make_shared<DirLight>(glm::vec3{-0, -1, -0}, glm::vec3{1, 1, 1}); pl2->ambient_intensity = 0.2f; pl2->set_casts_shadow(true); pl2->diffuse_intensity = 0.0f; renderer.add_light(pl2); auto cube = std::make_shared<RenderObject>(cube_mesh); renderer.add_object(cube); /* for(auto& sponza_mesh: sponza_meshes) { auto mesh = std::make_shared<RenderObject>(sponza_mesh); mesh->scale({0.01, 0.01, 0.01}); renderer.add_object(mesh); } */ for(int i = -5; i < 5; i++) { for(int j = -5; j < 5; j++) { auto floor = std::make_shared<RenderObject>(floor_mesh); floor->translate({i * 2,-1,j * 2}); renderer.add_object(floor); } } std::shared_ptr<SkyBox> sky = std::make_shared<SkyBox>(camera, skydome_mesh); sky->scale({2,2,2}); renderer.set_skybox(sky); Input::on(GLFW_KEY_I, [&] { renderer.get_shown_light()->translate({ 0.01f, 0, 0}); }, true); Input::on(GLFW_KEY_K, [&] { renderer.get_shown_light()->translate({-0.01f, 0, 0}); }, true); Input::on(GLFW_KEY_J, [&] { renderer.get_shown_light()->translate({0, 0, 0.01f}); }, true); Input::on(GLFW_KEY_L, [&] { renderer.get_shown_light()->translate({0, 0, -0.01f}); }, true); Input::on(GLFW_KEY_O, [&] { renderer.get_shown_light()->translate({0, 0.01f, 0}); }, true); Input::on(GLFW_KEY_U, [&] { renderer.get_shown_light()->translate({0,-0.01f, 0}); }, true); Input::on(GLFW_KEY_PAGE_UP, [&] { if(selected_light < renderer.light_count()) { renderer.show_single_light(++selected_light); } }, false); Input::on(GLFW_KEY_PAGE_DOWN, [&] { if(selected_light > 0) { renderer.show_single_light(--selected_light); } }, false); Input::on(GLFW_KEY_1, [&] { renderer.toggle_shadow_map(); }, false); Input::on(GLFW_KEY_P, [&] { auto light = std::make_shared<SpotLight>(camera.pos, -camera.dir, glm::vec3{1,1,1}); light->ambient_intensity = 0.0f; light->diffuse_intensity = 2.0f; light->set_casts_shadow(true); renderer.add_light(light); std::cout << "Amount of lights: " << renderer.light_count() << "\n"; }, false); Input::on(GLFW_KEY_RIGHT_CONTROL, [&] { renderer.show_single_light(-1); }, false); bool draw_main = true; Input::on(GLFW_KEY_T, [&] { draw_main = !draw_main; }, false); float i = 0; camera.translate({0, 2, 0}); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); Input::handle_input(); rotate_camera(camera); renderer.pre_render(); if(draw_main) { renderer.render(); } draw_rain(&renderer); glfwSwapBuffers(window); Input::reset_delta(); if(i > 360) { i=0; } i += 0.1f; calcFPS(window, 1.0, "Current FPS: "); checkForGlError(); } glfwDestroyWindow(window); glfwTerminate(); return 0; } <commit_msg>Fixes<commit_after>#define GLM_FORCE_RADIANS #define PI 3.14159265358979 #include <GL/glew.h> #include <glfw3.h> #include <glm/glm.hpp> #include <iostream> #include <math.h> #include <stdio.h> #include <stdlib.h> #include "gfx/Renderer.hpp" #include "gfx/VertexArray.hpp" #include "gfx/SkyBox.hpp" #include "gfx/importer/ObjLoader.hpp" #include "gfx/lights/Light.hpp" #include "gfx/lights/PointLight.hpp" #include "gfx/lights/DirLight.hpp" #include "gfx/shader/SimpleShader.hpp" #include "input/Actions.hpp" #include "input/Input.hpp" #include "DebugUtils.h" glm::vec3 get_random_color() { auto r = ((rand() % 100)/100.0); auto g = ((rand() % 100)/100.0); auto b = ((rand() % 100)/100.0); return glm::normalize(glm::vec3{r, g, b}); } std::vector<std::pair<glm::vec3, glm::vec3>> rain; void draw_rain(Renderer* r) { static float speed = 0.5; //if((rand() % 100)/100.0 < 0.5) { //for(int i = 0; i < 5; i++) { { auto x = ((rand() % 100)/100.0) * 10.0f; auto y = 20; auto z = ((rand() % 100)/100.0) * 10.0f; glm::vec3 from = glm::vec3(x,y,z); glm::vec3 to = from + glm::vec3{5, -16, 5}; rain.push_back(std::make_pair(from, to)); } std::vector<std::pair<glm::vec3, glm::vec3>> new_rain; for(auto& rain_pos: rain) { auto& from = std::get<0>(rain_pos); auto& to = std::get<1>(rain_pos); auto dir = glm::normalize(to - from); from += dir * speed; to += dir * speed; if(from.y > 0) { new_rain.push_back(rain_pos); } } r->draw_lines(rain, {0.1, 0.1, 0.1}); rain = new_rain; } static void error_callback(int error, const char* description) { fputs(description, stderr); } float step = 0.01f; int selected_light = -1; static void scroll_callback(GLFWwindow* window, double x_offset, double y_offset) { step = fmax(0.01f, fmin(step * pow(1.5, y_offset), 5)); } void rotate_camera(Camera& camera) { camera.rotate(-Input::get_mouse_dx() / 100.0f, camera.up); camera.rotate(Input::get_mouse_dy() / 100.0f, glm::cross(camera.up, camera.dir)); } const int width = 1024; const int height = 768; int main(int argc, char ** argv) { glfwSetErrorCallback(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* window = glfwCreateWindow(width, height, "glHondo", NULL, NULL); if (!window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(window); glewExperimental = GL_TRUE; GLenum err = glewInit(); //To discard error 1280 from glewInit(). glGetError(); if(GLEW_OK != err) std::cout << glewGetErrorString(err) << std::endl; { const GLubyte* renderer = glGetString(GL_RENDERER); const GLubyte* version = glGetString(GL_VERSION); printf("Renderer: %s\n", renderer); printf("Version: %s\n", version); glfwSetCursorPosCallback(window, Input::cursor_pos_callback); glfwSetKeyCallback(window, Input::key_callback); glfwSetScrollCallback(window, scroll_callback); Input::set_active_window(window); } Renderer renderer(width, height); auto& camera = renderer.get_camera(); Input::on(Actions::Forward, [&]() { camera.move_forward(step); }); Input::on(Actions::Backward, [&]() { camera.move_forward(-step); }); Input::on(Actions::Left, [&]() { camera.move_right(-step); }); Input::on(Actions::Right, [&]() { camera.move_right(step); }); Input::on(Actions::Up, [&]() { camera.translate({0, step, 0}); }); Input::on(Actions::Down, [&]() { camera.translate({0, -step, 0}); }); Input::on(GLFW_KEY_Z, [&] { renderer.toggle_wireframe(); }); Input::on(GLFW_KEY_G, []() { Input::lock_mouse(); }); ObjLoader loader; //loader.preload_file("assets/sponza.obj"); loader.preload_file("assets/Cube.obj"); loader.preload_file("assets/Floor.obj"); loader.preload_file("assets/sphere.obj"); loader.preload_file("assets/SkyDome16.obj"); std::cout << "Load files\n"; loader.load_files(); std::cout << "Loading files done\n"; Mesh skydome_mesh = loader.get_meshes("assets/SkyDome16.obj")[0]; Mesh cube_mesh = loader.get_meshes("assets/Cube.obj")[0]; Mesh sphere_mesh = loader.get_meshes("assets/sphere.obj")[0]; Mesh floor_mesh = loader.get_meshes("assets/Floor.obj")[0]; //std::vector<Mesh> sponza_meshes = loader.get_meshes("assets/sponza.obj"); auto pl2 = std::make_shared<DirLight>(glm::vec3{-0, -1, -0}, glm::vec3{1, 1, 1}); pl2->ambient_intensity = 0.2f; pl2->set_casts_shadow(true); pl2->diffuse_intensity = 0.0f; renderer.add_light(pl2); auto sphere = std::make_shared<RenderObject>(sphere_mesh); sphere->translate({0, 1, 2}); sphere->scale({0.5, 0.5, 0.5}); renderer.add_object(sphere); auto cube = std::make_shared<RenderObject>(cube_mesh); renderer.add_object(cube); /* for(auto& sponza_mesh: sponza_meshes) { auto mesh = std::make_shared<RenderObject>(sponza_mesh); mesh->scale({0.01, 0.01, 0.01}); renderer.add_object(mesh); } */ for(int i = -5; i < 5; i++) { for(int j = -5; j < 5; j++) { auto floor = std::make_shared<RenderObject>(floor_mesh); floor->translate({i * 2,-1,j * 2}); renderer.add_object(floor); } } std::shared_ptr<SkyBox> sky = std::make_shared<SkyBox>(camera, skydome_mesh); sky->scale({2,2,2}); renderer.set_skybox(sky); Input::on(GLFW_KEY_I, [&] { renderer.get_shown_light()->translate({ 0.01f, 0, 0}); }, true); Input::on(GLFW_KEY_K, [&] { renderer.get_shown_light()->translate({-0.01f, 0, 0}); }, true); Input::on(GLFW_KEY_J, [&] { renderer.get_shown_light()->translate({0, 0, 0.01f}); }, true); Input::on(GLFW_KEY_L, [&] { renderer.get_shown_light()->translate({0, 0, -0.01f}); }, true); Input::on(GLFW_KEY_O, [&] { renderer.get_shown_light()->translate({0, 0.01f, 0}); }, true); Input::on(GLFW_KEY_U, [&] { renderer.get_shown_light()->translate({0, -0.01f, 0}); }, true); Input::on(GLFW_KEY_PAGE_UP, [&] { if(selected_light < renderer.light_count()) { renderer.show_single_light(++selected_light); } }, false); Input::on(GLFW_KEY_DELETE, [&] { renderer.clear_lights(); }, false); Input::on(GLFW_KEY_PAGE_DOWN, [&] { if(selected_light > 0) { renderer.show_single_light(--selected_light); } }, false); Input::on(GLFW_KEY_1, [&] { renderer.toggle_shadow_map(); }, false); Input::on(GLFW_KEY_P, [&] { auto light = std::make_shared<SpotLight>(camera.pos, camera.dir, glm::vec3{1,1,1}); light->ambient_intensity = 0.0f; light->diffuse_intensity = 2.0f; light->set_casts_shadow(true); renderer.add_light(light); std::cout << "Amount of lights: " << renderer.light_count() << "\n"; }, false); Input::on(GLFW_KEY_RIGHT_CONTROL, [&] { renderer.show_single_light(-1); }, false); bool draw_main = true; Input::on(GLFW_KEY_T, [&] { draw_main = !draw_main; }, false); float i = 0; camera.translate({0, 2, 0}); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); Input::handle_input(); rotate_camera(camera); renderer.pre_render(); if(draw_main) { renderer.render(); } draw_rain(&renderer); glfwSwapBuffers(window); Input::reset_delta(); if(i > 360) { i=0; } i += 0.1f; calcFPS(window, 1.0, "Current FPS: "); checkForGlError(); } glfwDestroyWindow(window); glfwTerminate(); return 0; } <|endoftext|>
<commit_before>a1ad3e78-2e4e-11e5-9284-b827eb9e62be<commit_msg>a1b241b6-2e4e-11e5-9284-b827eb9e62be<commit_after>a1b241b6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>#include "Video/ScreenBuffer.hh" #include "SDLConfig.hh" namespace RAGE { namespace SDL { ScreenBuffer::ScreenBuffer(int width, int height, int bpp) throw (std::logic_error) : m_width(width), m_height(height),m_bpp(bpp), m_background(RGBColor(0,0,0)), m_initcb(NULL),m_resizecb(NULL), m_newframecb(NULL), m_rendercb(NULL) { //setting the static videoInfo to be used by all surfaces... BaseSurface::_vinfo = &m_videoinfo; //force usage of DEFAULT_DISPLAY_WIDTH & DEFAULT_DISPLAY_HEIGHT when only one param is equal to 0. if ((width == 0 && height != 0) || (width != 0 && height == 0)) { width = DEFAULT_DISPLAY_WIDTH; height = DEFAULT_DISPLAY_HEIGHT; } //TODO get rid of default display size and try 4/3 size, or pick first of suggested size by video info //Both equal to 0 means use dekstop/current mode. if (width == 0 && height == 0) { width = VideoSurface::getVideoInfo()->get_current_width(); height = VideoSurface::getVideoInfo()->get_current_height(); } if ( bpp == 0 ) //here 0 means autodetection { bpp=VideoSurface::getSuggestedBPP(width, height); } else { //TODO : check that the value of bpp asked for is supported... } m_width = width; m_height = height; m_bpp = bpp; //but beware about bpp == 0... if (m_bpp == 0 ) {//0 as return code mean the current format is not supported Log << nl << "The requested video mode is not supported under any bit depth. Screen creation cancelled !"; throw std::logic_error("VideoSurface::getSuggestedBPP(width, height) returned 0"); } } //recreating Engine here to make sure both origin and destination engines are independant. //maybe not really needed, but safer in case of copy ( or should we completely forbid copy ? ) ScreenBuffer::ScreenBuffer( const ScreenBuffer & sb ) : m_width(sb.m_width), m_height(sb.m_height),m_bpp(sb.m_bpp), m_background(sb.m_background), m_initcb(sb.m_initcb),m_resizecb(sb.m_resizecb), m_newframecb(sb.m_newframecb), m_rendercb(sb.m_rendercb) { //warning no protection offered here in case of wrong / unsupported size ( for the moment ) } ScreenBuffer::~ScreenBuffer() { BaseSurface::_vinfo = NULL; } bool ScreenBuffer::setResizable(bool val) { bool res = true; if (!m_screen.get()) //if not already created, set the static flag. VideoSurface::setResizable(val); else if (m_screen->isResizableset() !=val ) //if called inside mainLoop while screen is active { hide(); VideoSurface::setResizable(val); //set static flag if (! show()) //reset the screen res=false; } return res; } bool ScreenBuffer::setFullscreen(bool val) { #ifdef DEBUG Log << nl << "Window::setFullscreen(" << val << ") called" << std::endl; #endif bool res = true; if (!m_screen.get()) { VideoSurface::setFullscreen(val); } else { #ifdef DEBUG Log << nl << m_screen->isFullScreenset() << " != " << val << std::endl; #endif if (m_screen->isFullScreenset() != val ) //if called inside mainLoop while screen is active { hide(); VideoSurface::setFullscreen(val); if (! show() )//resetDisplay(m_screen->getWidth(),m_screen->getHeight(),m_screen->getBPP())) { res=false; } } } #ifdef DEBUG Log << nl << "Window::setFullscreen(" << val << ") done" << std::endl; #endif return res; } bool ScreenBuffer::setNoFrame(bool val) { bool res = true; if (!m_screen.get()) VideoSurface::setNoFrame(val); else if (m_screen->isNoFrameset() !=val ) //if called inside mainLoop while screen is active { hide(); VideoSurface::setNoFrame(val); if (! show() ) //resetDisplay(m_screen->getWidth(),m_screen->getHeight(),m_screen->getBPP())) res=false; } return res; } #ifdef HAVE_OPENGL bool ScreenBuffer::setOpenGL(bool val) { bool res = true; if (!m_screen.get()) { VideoSurface::setOpenGL(val); } else if ( m_screen->isOpenGLset() !=val ) //if called inside mainLoop while screen is active { hide(); VideoSurface::setOpenGL(val); if (! show() )//resetDisplay(m_screen->getWidth(),m_screen->getHeight(),m_screen->getBPP())) res=false; } return res; } #endif //to check the current properties of the display bool ScreenBuffer::isFullscreen() { if (m_screen.get()) { return m_screen->isFullScreenset(); } else { return ( SDL_FULLSCREEN & VideoSurface::_defaultflags ) != 0; } } bool ScreenBuffer::isResizable() { if (m_screen.get()) { return m_screen->isResizableset(); } else { return ( SDL_RESIZABLE & VideoSurface::_defaultflags ) != 0; } } bool ScreenBuffer::isOpenGL() { if (m_screen.get()) { return m_screen->isOpenGLset(); } else { return ( SDL_OPENGL & VideoSurface::_defaultflags ) != 0; } } bool ScreenBuffer::isNoFrame() { if (m_screen.get()) { return m_screen->isNoFrameset(); } else { return ( SDL_NOFRAME & VideoSurface::_defaultflags ) != 0; } } void ScreenBuffer::applyBGColor() const { if (m_screen.get()) // if auto pointer valid { #ifdef HAVE_OPENGL if (m_screen->isOpenGLset()) { glClearColor(static_cast<float> (m_background.getR() ) / 255.0f, static_cast<float> (m_background.getG() ) / 255.0f,static_cast<float> (m_background.getB() ) / 255.0f,0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } else { #endif //TODO background can be null, andthis will not be called.... ( speed improvemnt ) m_screen->fill(m_background); #ifdef HAVE_OPENGL } #endif } } bool ScreenBuffer::show() { #ifdef DEBUG Log << nl << "SceenBuffer::show() called ..." << std::endl; #endif if ( m_screen.get() != NULL ) // no need to reset the display { //if reset is wanted the buffer shoul be recreated return true; } //else the screen hasnt been displayed yet, or has been hidden. bool res = false; Log << nl <<"SDL is using " << m_width << "x" << m_height << "@" <<m_bpp; //create a new screen try { if ( isOpenGL() ) { m_screen.reset(new VideoGLSurface(m_width, m_height, m_bpp)); } else { m_screen.reset(new VideoSurface(m_width, m_height, m_bpp)); } //initializing engine m_engine.init(m_width, m_height); //calling user init callback if it exists if ( m_initcb ) m_initcb->call( m_width, m_height ); applyBGColor(); res=true; } catch(std::exception & e) { Log << nl << " Exception caught in Window::resetDisplay() : " << e.what(); res=false; } #ifdef DEBUG Log << nl << "ScreenBuffer::show() done." << std::endl; #endif return res; } bool ScreenBuffer::hide() { delete m_screen.release();// to test... } bool ScreenBuffer::resize (int width, int height) { #ifdef DEBUG Log << nl << "Screen::resize() called ..."; #endif bool res = true; if (m_screen.get()) { res = res && m_screen->resize(width,height);//doesnt keep content //calling our engine resize method res = res && m_engine.resize(width,height); //calling user callback for resize if it exists if ( m_resizecb ) m_resizecb->call(width, height); //this order otherwise we lose opengl context from the engine just after the resize ( reinit ) //because screen resize recreates the window, and lose opengl context as documented in SDL docs... applyBGColor(); } else { if (width>0) { m_width = width; } if (height>0) { m_height= height; } } #ifdef DEBUG Log << nl << "ScreenBuffer::resize() done."; #endif //Forcing the refresh (display the backcolor) m_screen->refresh(); return res; } bool ScreenBuffer::renderpass( unsigned long framerate, unsigned long& lastframe) { //Callback for preparing new frame if ( m_newframecb ) m_newframecb->call( framerate, SDL_GetTicks() - lastframe ); //applying the background //if (!ShowingLoadingScreen) applyBGColor(); //if (!ShowingLoadingScreen) if ( m_rendercb ) m_rendercb->call( *m_screen ); //calling our engine render function ( on top of user render ) //TODO : add a timer if not demo release... m_engine.render(*m_screen); //refresh screen //Log << nl << "before :" << SDL_GetTicks() - lastframe ; if ( SDL_GetTicks() - lastframe < 1000/framerate)//wait if needed - IMPORTANT otherwise the next value is far too high (not 0) SDL_Delay( 1000/framerate - ( SDL_GetTicks() - lastframe ) ); m_screen->refresh(); //Log << nl << "after :" << SDL_GetTicks() - lastframe ; lastframe=SDL_GetTicks(); //calling engine for postrender events //m_engine ->postrender(); } } // SDL } // RAGE <commit_msg>stupid gcc mistakes removed^^<commit_after>#include "Video/ScreenBuffer.hh" #include "SDLConfig.hh" namespace RAGE { namespace SDL { ScreenBuffer::ScreenBuffer(int width, int height, int bpp) throw (std::logic_error) : m_width(width), m_height(height),m_bpp(bpp), m_background(RGBColor(0,0,0)), m_initcb(NULL),m_resizecb(NULL), m_newframecb(NULL), m_rendercb(NULL) { //setting the static videoInfo to be used by all surfaces... BaseSurface::_vinfo = &m_videoinfo; //force usage of DEFAULT_DISPLAY_WIDTH & DEFAULT_DISPLAY_HEIGHT when only one param is equal to 0. if ((width == 0 && height != 0) || (width != 0 && height == 0)) { width = DEFAULT_DISPLAY_WIDTH; height = DEFAULT_DISPLAY_HEIGHT; } //TODO get rid of default display size and try 4/3 size, or pick first of suggested size by video info //Both equal to 0 means use dekstop/current mode. if (width == 0 && height == 0) { width = VideoSurface::getVideoInfo()->get_current_width(); height = VideoSurface::getVideoInfo()->get_current_height(); } if ( bpp == 0 ) //here 0 means autodetection { bpp=VideoSurface::getSuggestedBPP(width, height); } else { //TODO : check that the value of bpp asked for is supported... } m_width = width; m_height = height; m_bpp = bpp; //but beware about bpp == 0... if (m_bpp == 0 ) {//0 as return code mean the current format is not supported Log << nl << "The requested video mode is not supported under any bit depth. Screen creation cancelled !"; throw std::logic_error("VideoSurface::getSuggestedBPP(width, height) returned 0"); } } //recreating Engine here to make sure both origin and destination engines are independant. //maybe not really needed, but safer in case of copy ( or should we completely forbid copy ? ) ScreenBuffer::ScreenBuffer( const ScreenBuffer & sb ) : m_width(sb.m_width), m_height(sb.m_height),m_bpp(sb.m_bpp), m_background(sb.m_background), m_initcb(sb.m_initcb),m_resizecb(sb.m_resizecb), m_newframecb(sb.m_newframecb), m_rendercb(sb.m_rendercb) { //warning no protection offered here in case of wrong / unsupported size ( for the moment ) } ScreenBuffer::~ScreenBuffer() { BaseSurface::_vinfo = NULL; } bool ScreenBuffer::setResizable(bool val) { bool res = true; if (!m_screen.get()) //if not already created, set the static flag. VideoSurface::setResizable(val); else if (m_screen->isResizableset() !=val ) //if called inside mainLoop while screen is active { hide(); VideoSurface::setResizable(val); //set static flag if (! show()) //reset the screen res=false; } return res; } bool ScreenBuffer::setFullscreen(bool val) { #ifdef DEBUG Log << nl << "Window::setFullscreen(" << val << ") called" << std::endl; #endif bool res = true; if (!m_screen.get()) { VideoSurface::setFullscreen(val); } else { #ifdef DEBUG Log << nl << m_screen->isFullScreenset() << " != " << val << std::endl; #endif if (m_screen->isFullScreenset() != val ) //if called inside mainLoop while screen is active { hide(); VideoSurface::setFullscreen(val); if (! show() )//resetDisplay(m_screen->getWidth(),m_screen->getHeight(),m_screen->getBPP())) { res=false; } } } #ifdef DEBUG Log << nl << "Window::setFullscreen(" << val << ") done" << std::endl; #endif return res; } bool ScreenBuffer::setNoFrame(bool val) { bool res = true; if (!m_screen.get()) VideoSurface::setNoFrame(val); else if (m_screen->isNoFrameset() !=val ) //if called inside mainLoop while screen is active { hide(); VideoSurface::setNoFrame(val); if (! show() ) //resetDisplay(m_screen->getWidth(),m_screen->getHeight(),m_screen->getBPP())) res=false; } return res; } #ifdef HAVE_OPENGL bool ScreenBuffer::setOpenGL(bool val) { bool res = true; if (!m_screen.get()) { VideoSurface::setOpenGL(val); } else if ( m_screen->isOpenGLset() !=val ) //if called inside mainLoop while screen is active { hide(); VideoSurface::setOpenGL(val); if (! show() )//resetDisplay(m_screen->getWidth(),m_screen->getHeight(),m_screen->getBPP())) res=false; } return res; } #endif //to check the current properties of the display bool ScreenBuffer::isFullscreen() { if (m_screen.get()) { return m_screen->isFullScreenset(); } else { return ( SDL_FULLSCREEN & VideoSurface::_defaultflags ) != 0; } } bool ScreenBuffer::isResizable() { if (m_screen.get()) { return m_screen->isResizableset(); } else { return ( SDL_RESIZABLE & VideoSurface::_defaultflags ) != 0; } } bool ScreenBuffer::isOpenGL() { if (m_screen.get()) { return m_screen->isOpenGLset(); } else { return ( SDL_OPENGL & VideoSurface::_defaultflags ) != 0; } } bool ScreenBuffer::isNoFrame() { if (m_screen.get()) { return m_screen->isNoFrameset(); } else { return ( SDL_NOFRAME & VideoSurface::_defaultflags ) != 0; } } void ScreenBuffer::applyBGColor() const { if (m_screen.get()) // if auto pointer valid { #ifdef HAVE_OPENGL if (m_screen->isOpenGLset()) { glClearColor(static_cast<float> (m_background.getR() ) / 255.0f, static_cast<float> (m_background.getG() ) / 255.0f,static_cast<float> (m_background.getB() ) / 255.0f,0.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } else { #endif //TODO background can be null, andthis will not be called.... ( speed improvemnt ) m_screen->fill(m_background); #ifdef HAVE_OPENGL } #endif } } bool ScreenBuffer::show() { #ifdef DEBUG Log << nl << "SceenBuffer::show() called ..." << std::endl; #endif if ( m_screen.get() != NULL ) // no need to reset the display { //if reset is wanted the buffer shoul be recreated return true; } //else the screen hasnt been displayed yet, or has been hidden. bool res = false; Log << nl <<"SDL is using " << m_width << "x" << m_height << "@" <<m_bpp; //create a new screen try { if ( isOpenGL() ) { m_screen.reset(new VideoGLSurface(m_width, m_height, m_bpp)); } else { m_screen.reset(new VideoSurface(m_width, m_height, m_bpp)); } //initializing engine m_engine.init(m_width, m_height); //calling user init callback if it exists if ( m_initcb ) m_initcb->call( m_width, m_height ); applyBGColor(); res=true; } catch(std::exception & e) { Log << nl << " Exception caught in Window::resetDisplay() : " << e.what(); res=false; } #ifdef DEBUG Log << nl << "ScreenBuffer::show() done." << std::endl; #endif return res; } bool ScreenBuffer::hide() { delete m_screen.release();// to test... return true; //not used for now } bool ScreenBuffer::resize (int width, int height) { #ifdef DEBUG Log << nl << "Screen::resize() called ..."; #endif bool res = true; if (m_screen.get()) { res = res && m_screen->resize(width,height);//doesnt keep content //calling our engine resize method res = res && m_engine.resize(width,height); //calling user callback for resize if it exists if ( m_resizecb ) m_resizecb->call(width, height); //this order otherwise we lose opengl context from the engine just after the resize ( reinit ) //because screen resize recreates the window, and lose opengl context as documented in SDL docs... applyBGColor(); } else { if (width>0) { m_width = width; } if (height>0) { m_height= height; } } #ifdef DEBUG Log << nl << "ScreenBuffer::resize() done."; #endif //Forcing the refresh (display the backcolor) m_screen->refresh(); return res; } bool ScreenBuffer::renderpass( unsigned long framerate, unsigned long& lastframe) { //Callback for preparing new frame if ( m_newframecb ) m_newframecb->call( framerate, SDL_GetTicks() - lastframe ); //applying the background //if (!ShowingLoadingScreen) applyBGColor(); //if (!ShowingLoadingScreen) if ( m_rendercb ) m_rendercb->call( *m_screen ); //calling our engine render function ( on top of user render ) //TODO : add a timer if not demo release... m_engine.render(*m_screen); //refresh screen //Log << nl << "before :" << SDL_GetTicks() - lastframe ; if ( SDL_GetTicks() - lastframe < 1000/framerate)//wait if needed - IMPORTANT otherwise the next value is far too high (not 0) SDL_Delay( 1000/framerate - ( SDL_GetTicks() - lastframe ) ); m_screen->refresh(); //Log << nl << "after :" << SDL_GetTicks() - lastframe ; lastframe=SDL_GetTicks(); //calling engine for postrender events //m_engine ->postrender(); return true; //not used for now } } // SDL } // RAGE <|endoftext|>
<commit_before>ceb51b86-2e4c-11e5-9284-b827eb9e62be<commit_msg>ceba0e66-2e4c-11e5-9284-b827eb9e62be<commit_after>ceba0e66-2e4c-11e5-9284-b827eb9e62be<|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // // FlowManager.cpp // // Access to the GPII flowmanager to log in and out // // Project Files: // FlowManager.cpp // FlowManager.h // /////////////////////////////////////////////////////////////////////////////// #include <FlowManager.h> #include <libcurl\curl.h> #ifdef __MINGW_H // not included in mingw headers extern void WINAPI OutputDebugString( LPCTSTR lpOutputString ); #endif // Set TRUE to use fiddler2.com to debug http #if defined(_DEBUG) #define USE_FIDDLER FALSE #endif //--------------------------------------------------------- // Flow Manager Constants //--------------------------------------------------------- const char * const FLOW_MANAGER_URL = "http://localhost:8081/user"; const char * const FLOW_LOGIN = "login"; const char * const FLOW_LOGOUT = "logout"; /////////////////////////////////////////////////////////////////////////////// // // FUNCTION: MakeCurlRequest(char szUser,char szAction) // // PURPOSE: Uses libcurl to make a HTTP GET request to a specified URL. // // EXAMPLES: // // http://localhost:8081/user/123/login // // http://localhost:8081/user/123/logout // /////////////////////////////////////////////////////////////////////////////// static int _MakeCurlRequest(const char* szUser, const char* szAction) { static const int MAX_BUFFER = 256; if (lstrlen(szUser) > 0) { CURL *curl = curl_easy_init(); if (curl) { char szRequest[MAX_BUFFER]; char * szUserEscaped = curl_easy_escape(curl, szUser, 0); wsprintf(szRequest,"%s/%s/%s",FLOW_MANAGER_URL,szUserEscaped,szAction); #ifdef _DEBUG OutputDebugString(szRequest); // will show in gdb #endif #if defined(USE_FIDDLER) (void) curl_easy_setopt(curl, CURLOPT_PROXY, "127.0.0.1:8888"); // use http://fiddler2.com to monitor HTTP #endif (void) curl_easy_setopt(curl, CURLOPT_URL, szRequest); // TODO Check the response code and handle errors. CURLcode responseCode = curl_easy_perform(curl); // expect CURLE_WRITE_ERROR as no buffer given for incoming data (void) responseCode; // tell compiler we're not doing anything with it - just for debugging curl_free(szUserEscaped); curl_easy_cleanup(curl); return 1; } } return 0; } void FlowManagerLogin(const char * szToken) { _MakeCurlRequest(szToken, FLOW_LOGIN); } void FlowManagerLogout(const char * szToken) // FIXME should we keep state or can we have multiple concurrent logins? { _MakeCurlRequest(szToken, FLOW_LOGOUT); } // End of file <commit_msg>removed tabs<commit_after>/////////////////////////////////////////////////////////////////////////////// // // FlowManager.cpp // // Access to the GPII flowmanager to log in and out // // Project Files: // FlowManager.cpp // FlowManager.h // /////////////////////////////////////////////////////////////////////////////// #include <FlowManager.h> #include <libcurl\curl.h> #ifdef __MINGW_H // not included in mingw headers extern void WINAPI OutputDebugString( LPCTSTR lpOutputString ); #endif // Set TRUE to use fiddler2.com to debug http #if defined(_DEBUG) #define USE_FIDDLER FALSE #endif //--------------------------------------------------------- // Flow Manager Constants //--------------------------------------------------------- const char * const FLOW_MANAGER_URL = "http://localhost:8081/user"; const char * const FLOW_LOGIN = "login"; const char * const FLOW_LOGOUT = "logout"; /////////////////////////////////////////////////////////////////////////////// // // FUNCTION: MakeCurlRequest(char szUser,char szAction) // // PURPOSE: Uses libcurl to make a HTTP GET request to a specified URL. // // EXAMPLES: // // http://localhost:8081/user/123/login // // http://localhost:8081/user/123/logout // /////////////////////////////////////////////////////////////////////////////// static int _MakeCurlRequest(const char* szUser, const char* szAction) { static const int MAX_BUFFER = 256; if (lstrlen(szUser) > 0) { CURL *curl = curl_easy_init(); if (curl) { char szRequest[MAX_BUFFER]; char * szUserEscaped = curl_easy_escape(curl, szUser, 0); wsprintf(szRequest,"%s/%s/%s",FLOW_MANAGER_URL,szUserEscaped,szAction); #ifdef _DEBUG OutputDebugString(szRequest); // will show in VisualStudio and gdb OutputDebugString("\r\n"); #endif #if defined(USE_FIDDLER) (void) curl_easy_setopt(curl, CURLOPT_PROXY, "127.0.0.1:8888"); // use http://fiddler2.com to monitor HTTP #endif (void) curl_easy_setopt(curl, CURLOPT_URL, szRequest); // TODO Check the response code and handle errors. CURLcode responseCode = curl_easy_perform(curl); // expect CURLE_WRITE_ERROR as no buffer given for incoming data (void) responseCode; // tell compiler we're not doing anything with it - just for debugging curl_free(szUserEscaped); curl_easy_cleanup(curl); return 1; } } return 0; } void FlowManagerLogin(const char * szToken) { _MakeCurlRequest(szToken, FLOW_LOGIN); } void FlowManagerLogout(const char * szToken) // FIXME should we keep state or can we have multiple concurrent logins? { _MakeCurlRequest(szToken, FLOW_LOGOUT); } // End of file <|endoftext|>
<commit_before>#include <algorithm> #include <array> #include <iomanip> #include <curl/curl.h> #include <memory> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> #include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string update_check(""); size_t writefunction(const char *ptr, size_t size, size_t nmemb, void *userdata) { std::string *s = static_cast<std::string *>(userdata); s->append(ptr, size * nmemb); return size * nmemb; } std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } class Target { public: enum class Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } std::string checksum() const { return m_checksum; } void fetch() { std::cout << "pretending to fetch " << name() << std::endl; std::string path; std::ofstream ofs(name()); if (!ofs.good()) { auto elems = split(name(), '/'); for (size_t i = 0, k = elems.size(); i < k; ++i) //for (auto s : elems) { const std::string &s(elems[i]); if (s.size() && s != ".") { path.append((i > 0 ? "/" : "") + s); if (k > 1 && i < k - 1) { auto status = mkdir(path.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err == std::errc::file_exists) { std::cout << "error making dir: " << err.message() << std::endl; } } } std::cout << "the path: " << path << std::endl; } } ofs.open(path); if (ofs.good()) { std::cout << "opened path " << path << std::endl; } } if (ofs.good()) { const std::string md5("38eaad974c15e5f3119469f17e8e97a9"); //if (md5 != checksum()) { std::cout << "Downloading new " << name() << std::endl; std::string s; std::shared_ptr<CURL *> phandle = std::make_shared<CURL *>(curl_easy_init()); std::string url(patch_dir + name()); curl_easy_setopt(*phandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction); curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &s); //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0); curl_easy_perform(*phandle); curl_easy_cleanup(*phandle); phandle.reset(); ofs << s; ofs.close(); } //else { std::cout << name() << " already up to date." << std::endl; } } } Status status() { return Status::Nonexistent; } private: std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } class CurlGlobalInit { public: CurlGlobalInit() { curl_global_init(CURL_GLOBAL_ALL); } ~CurlGlobalInit() { curl_global_cleanup(); } }; bool file_checksum_test(const std::string &path, const std::string &checksum) { #define md_md5 #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ifstream::binary); const int length = 8192; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount()); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); std::for_each(std::begin(result), std::end(result), [&calcsum](unsigned char c) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); }); std::cout << calcsum.str() << std::endl; return calcsum.str() == checksum; } int main(int argc, char *argv[]) { CurlGlobalInit curl_global; std::string fetch; std::shared_ptr<CURL *> phandle = std::make_shared<CURL *>(curl_easy_init()); curl_easy_setopt(*phandle, CURLOPT_URL, listing.c_str()); curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction); curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch); //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0); curl_easy_perform(*phandle); curl_easy_cleanup(*phandle); phandle.reset(); //std::cout << fetch << std::endl; std::vector<std::string> v(split(fetch, '\n')); //split(fetch, '\n', v); //std::cout << v[1] << std::endl; std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(v), end = std::end(v); beg != end; ++beg) { auto w(split(*beg, '@')); /* for (const auto & sss : w) { std::cout << sss << ", " << std::endl; } */ Target t(w[0], w[w.size() - 1]); auto status = t.status(); if (status == Target::Status::Nonexistent) { new_targets.push_back(std::move(t)); } else if (status == Target::Status::Outdated) { old_targets.push_back(std::move(t)); } //std::cout << *beg << std::endl; } std::stringstream ss(fetch); std::string item; //std::vector<std::pair<std::string, std::string>> new_targets; while (std::getline(ss, item)) { //new_targets.push_back(item); } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; //for (auto &t : new_targets) { //std::cout << t << std::endl; //t.fetch(); } std::cout << new_targets[4] << std::endl; new_targets[1].fetch(); new_targets[4].fetch(); /* for (auto s : split(new_targets[4].name(), '/')) { if (s.length()) { std::cout << s << ", "; } } */ } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; for (auto &t : old_targets) { std::cout << t << std::endl; } } else { std::cout << "No targets out of date." << std::endl; } const std::string path = "bin/override/spells.2da"; const std::string checksum("38eaad974c15e5f3119469f17e8e97a9"); std::cout << "file checksum test: " << path << " = " << checksum << " : " << file_checksum_test(path, checksum) << std::endl; std::cout << std::endl; return 0; } <commit_msg>Use foreach loop now that we have std::array base.<commit_after>#include <algorithm> #include <array> #include <iomanip> #include <curl/curl.h> #include <memory> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> #include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string update_check(""); size_t writefunction(const char *ptr, size_t size, size_t nmemb, void *userdata) { std::string *s = static_cast<std::string *>(userdata); s->append(ptr, size * nmemb); return size * nmemb; } std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } class Target { public: enum class Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } std::string checksum() const { return m_checksum; } void fetch() { std::cout << "pretending to fetch " << name() << std::endl; std::string path; std::ofstream ofs(name()); if (!ofs.good()) { auto elems = split(name(), '/'); for (size_t i = 0, k = elems.size(); i < k; ++i) //for (auto s : elems) { const std::string &s(elems[i]); if (s.size() && s != ".") { path.append((i > 0 ? "/" : "") + s); if (k > 1 && i < k - 1) { auto status = mkdir(path.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err == std::errc::file_exists) { std::cout << "error making dir: " << err.message() << std::endl; } } } std::cout << "the path: " << path << std::endl; } } ofs.open(path); if (ofs.good()) { std::cout << "opened path " << path << std::endl; } } if (ofs.good()) { const std::string md5("38eaad974c15e5f3119469f17e8e97a9"); //if (md5 != checksum()) { std::cout << "Downloading new " << name() << std::endl; std::string s; std::shared_ptr<CURL *> phandle = std::make_shared<CURL *>(curl_easy_init()); std::string url(patch_dir + name()); curl_easy_setopt(*phandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction); curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &s); //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0); curl_easy_perform(*phandle); curl_easy_cleanup(*phandle); phandle.reset(); ofs << s; ofs.close(); } //else { std::cout << name() << " already up to date." << std::endl; } } } Status status() { return Status::Nonexistent; } private: std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } class CurlGlobalInit { public: CurlGlobalInit() { curl_global_init(CURL_GLOBAL_ALL); } ~CurlGlobalInit() { curl_global_cleanup(); } }; bool file_checksum_test(const std::string &path, const std::string &checksum) { #define md_md5 #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ifstream::binary); const int length = 8192; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount()); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); for (unsigned char c : result) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); } /* std::for_each(std::begin(result), std::end(result), [&calcsum](unsigned char c) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); }); */ std::cout << calcsum.str() << std::endl; return calcsum.str() == checksum; } int main(int argc, char *argv[]) { CurlGlobalInit curl_global; std::string fetch; std::shared_ptr<CURL *> phandle = std::make_shared<CURL *>(curl_easy_init()); curl_easy_setopt(*phandle, CURLOPT_URL, listing.c_str()); curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction); curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch); //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0); curl_easy_perform(*phandle); curl_easy_cleanup(*phandle); phandle.reset(); //std::cout << fetch << std::endl; std::vector<std::string> v(split(fetch, '\n')); //split(fetch, '\n', v); //std::cout << v[1] << std::endl; std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(v), end = std::end(v); beg != end; ++beg) { auto w(split(*beg, '@')); /* for (const auto & sss : w) { std::cout << sss << ", " << std::endl; } */ Target t(w[0], w[w.size() - 1]); auto status = t.status(); if (status == Target::Status::Nonexistent) { new_targets.push_back(std::move(t)); } else if (status == Target::Status::Outdated) { old_targets.push_back(std::move(t)); } //std::cout << *beg << std::endl; } std::stringstream ss(fetch); std::string item; //std::vector<std::pair<std::string, std::string>> new_targets; while (std::getline(ss, item)) { //new_targets.push_back(item); } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; //for (auto &t : new_targets) { //std::cout << t << std::endl; //t.fetch(); } std::cout << new_targets[4] << std::endl; new_targets[1].fetch(); new_targets[4].fetch(); /* for (auto s : split(new_targets[4].name(), '/')) { if (s.length()) { std::cout << s << ", "; } } */ } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; for (auto &t : old_targets) { std::cout << t << std::endl; } } else { std::cout << "No targets out of date." << std::endl; } const std::string path = "bin/override/spells.2da"; const std::string checksum("38eaad974c15e5f3119469f17e8e97a9"); std::cout << "file checksum test: " << path << " = " << checksum << " : " << file_checksum_test(path, checksum) << std::endl; std::cout << std::endl; return 0; } <|endoftext|>
<commit_before>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_EFFECTS_HPP #define ROSETTASTONE_EFFECTS_HPP #include <Rosetta/Enchants/Effect.hpp> namespace RosettaStone { //! //! \brief Effects class. //! //! This class lists specific effects such as Taunt, Poisonous and Stealth. //! class Effects { public: //! Creates effect that increases attack by \p n. static Effect* AttackN(int n) { return new Effect(GameTag::ATK, EffectOperator::ADD, n); } //! Creates effect that increases health by \p n. static Effect* HealthN(int n) { return new Effect(GameTag::HEALTH, EffectOperator::ADD, n); } //! Creates effect that increases attack and health by \p n. static std::vector<Effect*> AttackHealthN(int n) { return { AttackN(n), HealthN(n) }; } //! Creates effect that reduces cost by \p n. static Effect* ReduceCost(int n) { return new Effect(GameTag::COST, EffectOperator::SUB, n); } //! A minion ability which forces the opposing player to direct any //! melee attacks toward enemy targets with this ability. inline static Effect* Taunt = new Effect(GameTag::TAUNT, EffectOperator::SET, 1); //! A minion ability that causes any minion damaged by them to be destroyed. inline static Effect* Poisonous = new Effect(GameTag::POISONOUS, EffectOperator::SET, 1); //! An ability which causes a minion to ignore the next damage it receives. inline static Effect* DivineShield = new Effect(GameTag::DIVINE_SHIELD, EffectOperator::SET, 1); //! An ability which allows a character to attack twice per turn. inline static Effect* Windfury = new Effect(GameTag::WINDFURY, EffectOperator::SET, 1); //! An ability allowing a minion to attack the same turn it is summoned or //! brought under a new player's control. inline static Effect* Charge = new Effect(GameTag::CHARGE, EffectOperator::SET, 1); //! A minion ability which prevents that minion from being the target of //! enemy attacks, spells and effects until they attack. inline static Effect* Stealth = new Effect(GameTag::STEALTH, EffectOperator::SET, 1); }; } // namespace RosettaStone #endif // ROSETTASTONE_EFFECTS_HPP <commit_msg>feat(card-impl): Add effect 'Immune'<commit_after>// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_EFFECTS_HPP #define ROSETTASTONE_EFFECTS_HPP #include <Rosetta/Enchants/Effect.hpp> namespace RosettaStone { //! //! \brief Effects class. //! //! This class lists specific effects such as Taunt, Poisonous and Stealth. //! class Effects { public: //! Creates effect that increases attack by \p n. static Effect* AttackN(int n) { return new Effect(GameTag::ATK, EffectOperator::ADD, n); } //! Creates effect that increases health by \p n. static Effect* HealthN(int n) { return new Effect(GameTag::HEALTH, EffectOperator::ADD, n); } //! Creates effect that increases attack and health by \p n. static std::vector<Effect*> AttackHealthN(int n) { return { AttackN(n), HealthN(n) }; } //! Creates effect that reduces cost by \p n. static Effect* ReduceCost(int n) { return new Effect(GameTag::COST, EffectOperator::SUB, n); } //! A minion ability which forces the opposing player to direct any //! melee attacks toward enemy targets with this ability. inline static Effect* Taunt = new Effect(GameTag::TAUNT, EffectOperator::SET, 1); //! A minion ability that causes any minion damaged by them to be destroyed. inline static Effect* Poisonous = new Effect(GameTag::POISONOUS, EffectOperator::SET, 1); //! An ability which causes a minion to ignore the next damage it receives. inline static Effect* DivineShield = new Effect(GameTag::DIVINE_SHIELD, EffectOperator::SET, 1); //! An ability which allows a character to attack twice per turn. inline static Effect* Windfury = new Effect(GameTag::WINDFURY, EffectOperator::SET, 1); //! An ability allowing a minion to attack the same turn it is summoned or //! brought under a new player's control. inline static Effect* Charge = new Effect(GameTag::CHARGE, EffectOperator::SET, 1); //! A minion ability which prevents that minion from being the target of //! enemy attacks, spells and effects until they attack. inline static Effect* Stealth = new Effect(GameTag::STEALTH, EffectOperator::SET, 1); //! An ability that prevents characters from receiving any damage, and //! prevents the opponent from specifically targeting them with any type of //! action. inline static Effect* Immune = new Effect(GameTag::IMMUNE, EffectOperator::SET, 1); }; } // namespace RosettaStone #endif // ROSETTASTONE_EFFECTS_HPP <|endoftext|>
<commit_before>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkAddNewPropertyDialog.h" #include "QmitkPropertyItemDelegate.h" #include "QmitkPropertyItemModel.h" #include "QmitkPropertyItemSortFilterProxyModel.h" #include "QmitkPropertyTreeView.h" #include <berryIBerryPreferences.h> #include <berryQtStyleManager.h> #include <mitkIPropertyAliases.h> #include <mitkIPropertyDescriptions.h> #include <mitkIPropertyPersistence.h> #include <QmitkRenderWindow.h> #include <QPainter> #include <memory> const std::string QmitkPropertyTreeView::VIEW_ID = "org.mitk.views.properties"; QmitkPropertyTreeView::QmitkPropertyTreeView() : m_PropertyAliases(mitk::CoreServices::GetPropertyAliases(nullptr), nullptr), m_PropertyDescriptions(mitk::CoreServices::GetPropertyDescriptions(nullptr), nullptr), m_PropertyPersistence(mitk::CoreServices::GetPropertyPersistence(nullptr), nullptr), m_ProxyModel(nullptr), m_Model(nullptr), m_Delegate(nullptr), m_Renderer(nullptr) { } QmitkPropertyTreeView::~QmitkPropertyTreeView() { } void QmitkPropertyTreeView::SetFocus() { m_Controls.filterLineEdit->setFocus(); } void QmitkPropertyTreeView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) { if (m_Controls.propertyListComboBox->count() == 2) { QHash<QString, QmitkRenderWindow*> renderWindows = renderWindowPart->GetQmitkRenderWindows(); Q_FOREACH(QString renderWindow, renderWindows.keys()) { m_Controls.propertyListComboBox->insertItem(m_Controls.propertyListComboBox->count() - 1, QString("Data node: ") + renderWindow); } } } void QmitkPropertyTreeView::RenderWindowPartDeactivated(mitk::IRenderWindowPart*) { if (m_Controls.propertyListComboBox->count() > 2) { m_Controls.propertyListComboBox->clear(); m_Controls.propertyListComboBox->addItem("Data node: common"); m_Controls.propertyListComboBox->addItem("Base data"); } } void QmitkPropertyTreeView::CreateQtPartControl(QWidget* parent) { m_Controls.setupUi(parent); m_Controls.propertyListComboBox->addItem("Data node: common"); mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart(); if (renderWindowPart != nullptr) { QHash<QString, QmitkRenderWindow*> renderWindows = renderWindowPart->GetQmitkRenderWindows(); for(const auto& renderWindow : renderWindows.keys()) { m_Controls.propertyListComboBox->addItem(QString("Data node: ") + renderWindow); } } m_Controls.propertyListComboBox->addItem("Base data"); m_Controls.newButton->setEnabled(false); this->HideAllIcons(); m_ProxyModel = new QmitkPropertyItemSortFilterProxyModel(m_Controls.treeView); m_Model = new QmitkPropertyItemModel(m_ProxyModel); m_ProxyModel->setSourceModel(m_Model); m_ProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setDynamicSortFilter(true); m_Delegate = new QmitkPropertyItemDelegate(m_Controls.treeView); m_Controls.singleSlot->SetDataStorage(GetDataStorage()); m_Controls.singleSlot->SetSelectionIsOptional(true); m_Controls.singleSlot->SetAutoSelectNewNodes(true); m_Controls.singleSlot->SetEmptyInfo(QString("Please select a data node")); m_Controls.singleSlot->SetPopUpTitel(QString("Select data node")); m_SelectionServiceConnector = std::make_unique<QmitkSelectionServiceConnector>(); SetAsSelectionListener(true); m_Controls.filterLineEdit->setClearButtonEnabled(true); m_Controls.treeView->setItemDelegateForColumn(1, m_Delegate); m_Controls.treeView->setModel(m_ProxyModel); m_Controls.treeView->setColumnWidth(0, 160); m_Controls.treeView->sortByColumn(0, Qt::AscendingOrder); m_Controls.treeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_Controls.treeView->setSelectionMode(QAbstractItemView::SingleSelection); m_Controls.treeView->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::DoubleClicked); const int ICON_SIZE = 32; auto icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/tags.svg")); m_Controls.tagsLabel->setPixmap(icon.pixmap(ICON_SIZE)); icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/tag.svg")); m_Controls.tagLabel->setPixmap(icon.pixmap(ICON_SIZE)); icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/document-save.svg")); m_Controls.saveLabel->setPixmap(icon.pixmap(ICON_SIZE)); connect(m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &QmitkPropertyTreeView::OnCurrentSelectionChanged); connect(m_Controls.filterLineEdit, &QLineEdit::textChanged, this, &QmitkPropertyTreeView::OnFilterTextChanged); connect(m_Controls.propertyListComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &QmitkPropertyTreeView::OnPropertyListChanged); connect(m_Controls.newButton, &QPushButton::clicked, this, &QmitkPropertyTreeView::OnAddNewProperty); connect(m_Controls.treeView->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &QmitkPropertyTreeView::OnCurrentRowChanged); connect(m_Model, &QmitkPropertyItemModel::modelReset, this, &QmitkPropertyTreeView::OnModelReset); } void QmitkPropertyTreeView::SetAsSelectionListener(bool checked) { if (checked) { m_SelectionServiceConnector->AddPostSelectionListener(GetSite()->GetWorkbenchWindow()->GetSelectionService()); connect(m_SelectionServiceConnector.get(), &QmitkSelectionServiceConnector::ServiceSelectionChanged, m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::SetCurrentSelection); } else { m_SelectionServiceConnector->RemovePostSelectionListener(); disconnect(m_SelectionServiceConnector.get(), &QmitkSelectionServiceConnector::ServiceSelectionChanged, m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::SetCurrentSelection); } } QString QmitkPropertyTreeView::GetPropertyNameOrAlias(const QModelIndex& index) { QString propertyName; if (index.isValid()) { QModelIndex current = index; while (current.isValid()) { QString name = m_ProxyModel->data(m_ProxyModel->index(current.row(), 0, current.parent())).toString(); propertyName.prepend(propertyName.isEmpty() ? name : name.append('.')); current = current.parent(); } } return propertyName; } void QmitkPropertyTreeView::OnCurrentSelectionChanged(QList<mitk::DataNode::Pointer> nodes) { if (nodes.empty() || nodes.front().IsNull()) { m_SelectedNode = nullptr; this->SetPartName("Properties"); m_Model->SetPropertyList(nullptr); m_Delegate->SetPropertyList(nullptr); m_Controls.newButton->setEnabled(false); return; } // node is selected, create tree with node properties m_SelectedNode = nodes.front(); mitk::PropertyList* propertyList = m_Model->GetPropertyList(); if (m_Renderer == nullptr && m_Controls.propertyListComboBox->currentText() == "Base data") { propertyList = m_SelectedNode->GetData() != nullptr ? m_SelectedNode->GetData()->GetPropertyList() : nullptr; } else { propertyList = m_SelectedNode->GetPropertyList(m_Renderer); } QString selectionClassName = m_SelectedNode->GetData() != nullptr ? m_SelectedNode->GetData()->GetNameOfClass() : ""; m_SelectionClassName = selectionClassName.toStdString(); m_Model->SetPropertyList(propertyList, selectionClassName); m_Delegate->SetPropertyList(propertyList); m_Controls.newButton->setEnabled(true); if (!m_ProxyModel->filterRegExp().isEmpty()) { m_Controls.treeView->expandAll(); } } void QmitkPropertyTreeView::HideAllIcons() { m_Controls.tagLabel->hide(); m_Controls.tagsLabel->hide(); m_Controls.saveLabel->hide(); } void QmitkPropertyTreeView::OnCurrentRowChanged(const QModelIndex& current, const QModelIndex&) { if (current.isValid()) { QString name = this->GetPropertyNameOrAlias(current); if (!name.isEmpty()) { QString alias; bool isTrueName = true; std::string trueName = m_PropertyAliases->GetPropertyName(name.toStdString()); if (trueName.empty() && !m_SelectionClassName.empty()) trueName = m_PropertyAliases->GetPropertyName(name.toStdString(), m_SelectionClassName); if (!trueName.empty()) { alias = name; name = QString::fromStdString(trueName); isTrueName = false; } QString description = QString::fromStdString(m_PropertyDescriptions->GetDescription(name.toStdString())); std::vector<std::string> aliases; if (!isTrueName) { aliases = m_PropertyAliases->GetAliases(name.toStdString(), m_SelectionClassName); if (aliases.empty() && !m_SelectionClassName.empty()) aliases = m_PropertyAliases->GetAliases(name.toStdString()); } bool isPersistent = m_PropertyPersistence->HasInfo(name.toStdString()); if (!description.isEmpty() || !aliases.empty() || isPersistent) { QString customizedDescription; if (!aliases.empty()) { customizedDescription = "<h3 style=\"margin-bottom:0\">" + name + "</h3>"; std::size_t numAliases = aliases.size(); std::size_t lastAlias = numAliases - 1; for (std::size_t i = 0; i < numAliases; ++i) { customizedDescription += i != lastAlias ? "<h5 style=\"margin-top:0;margin-bottom:0\">" : "<h5 style=\"margin-top:0;margin-bottom:10px\">"; customizedDescription += QString::fromStdString(aliases[i]) + "</h5>"; } } else { customizedDescription = "<h3 style=\"margin-bottom:10px\">" + name + "</h3>"; } if (!description.isEmpty()) customizedDescription += "<p>" + description + "</p>"; m_Controls.tagsLabel->setVisible(!aliases.empty() && aliases.size() > 1); m_Controls.tagLabel->setVisible(!aliases.empty() && aliases.size() == 1); m_Controls.saveLabel->setVisible(isPersistent); m_Controls.descriptionLabel->setText(customizedDescription); m_Controls.descriptionLabel->show(); return; } } } m_Controls.descriptionLabel->hide(); this->HideAllIcons(); } void QmitkPropertyTreeView::OnPropertyListChanged(int index) { if (index == -1) return; QString renderer = m_Controls.propertyListComboBox->itemText(index); if (renderer.startsWith("Data node: ")) renderer = QString::fromStdString(renderer.toStdString().substr(11)); m_Renderer = nullptr; if (renderer != "common" && renderer != "Base data") { auto* renderWindowPart = this->GetRenderWindowPart(); if (nullptr != renderWindowPart) m_Renderer = renderWindowPart->GetQmitkRenderWindow(renderer)->GetRenderer(); } QList<mitk::DataNode::Pointer> nodes; if (m_SelectedNode.IsNotNull()) nodes << m_SelectedNode; this->OnCurrentSelectionChanged(nodes); } void QmitkPropertyTreeView::OnAddNewProperty() { std::unique_ptr<QmitkAddNewPropertyDialog> dialog(m_Controls.propertyListComboBox->currentText() != "Base data" ? new QmitkAddNewPropertyDialog(m_SelectedNode, m_Renderer) : new QmitkAddNewPropertyDialog(m_SelectedNode->GetData())); if (dialog->exec() == QDialog::Accepted) this->m_Model->Update(); } void QmitkPropertyTreeView::OnFilterTextChanged(const QString& filter) { m_ProxyModel->setFilterWildcard(filter); if (filter.isEmpty()) m_Controls.treeView->collapseAll(); else m_Controls.treeView->expandAll(); } void QmitkPropertyTreeView::OnModelReset() { m_Controls.descriptionLabel->hide(); this->HideAllIcons(); } <commit_msg>Fix initial selection and auto-selection of invisible nodes<commit_after>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "QmitkAddNewPropertyDialog.h" #include "QmitkPropertyItemDelegate.h" #include "QmitkPropertyItemModel.h" #include "QmitkPropertyItemSortFilterProxyModel.h" #include "QmitkPropertyTreeView.h" #include <berryIBerryPreferences.h> #include <berryQtStyleManager.h> #include <mitkIPropertyAliases.h> #include <mitkIPropertyDescriptions.h> #include <mitkIPropertyPersistence.h> #include <QmitkRenderWindow.h> #include <QPainter> #include <memory> namespace { QmitkAbstractNodeSelectionWidget::NodeList GetInitialSelection(berry::ISelection::ConstPointer selection) { if (selection.IsNotNull() && !selection->IsEmpty()) { auto* dataNodeSelection = dynamic_cast<const mitk::DataNodeSelection*>(selection.GetPointer()); if (nullptr != dataNodeSelection) { auto firstSelectedDataNode = dataNodeSelection->GetSelectedDataNodes().front(); if (firstSelectedDataNode.IsNotNull()) { QmitkAbstractNodeSelectionWidget::NodeList initialSelection; initialSelection.push_back(firstSelectedDataNode); return initialSelection; } } } return QmitkAbstractNodeSelectionWidget::NodeList(); } } const std::string QmitkPropertyTreeView::VIEW_ID = "org.mitk.views.properties"; QmitkPropertyTreeView::QmitkPropertyTreeView() : m_PropertyAliases(mitk::CoreServices::GetPropertyAliases(nullptr), nullptr), m_PropertyDescriptions(mitk::CoreServices::GetPropertyDescriptions(nullptr), nullptr), m_PropertyPersistence(mitk::CoreServices::GetPropertyPersistence(nullptr), nullptr), m_ProxyModel(nullptr), m_Model(nullptr), m_Delegate(nullptr), m_Renderer(nullptr) { } QmitkPropertyTreeView::~QmitkPropertyTreeView() { } void QmitkPropertyTreeView::SetFocus() { m_Controls.filterLineEdit->setFocus(); } void QmitkPropertyTreeView::RenderWindowPartActivated(mitk::IRenderWindowPart* renderWindowPart) { if (m_Controls.propertyListComboBox->count() == 2) { QHash<QString, QmitkRenderWindow*> renderWindows = renderWindowPart->GetQmitkRenderWindows(); Q_FOREACH(QString renderWindow, renderWindows.keys()) { m_Controls.propertyListComboBox->insertItem(m_Controls.propertyListComboBox->count() - 1, QString("Data node: ") + renderWindow); } } } void QmitkPropertyTreeView::RenderWindowPartDeactivated(mitk::IRenderWindowPart*) { if (m_Controls.propertyListComboBox->count() > 2) { m_Controls.propertyListComboBox->clear(); m_Controls.propertyListComboBox->addItem("Data node: common"); m_Controls.propertyListComboBox->addItem("Base data"); } } void QmitkPropertyTreeView::CreateQtPartControl(QWidget* parent) { m_Controls.setupUi(parent); m_Controls.propertyListComboBox->addItem("Data node: common"); mitk::IRenderWindowPart* renderWindowPart = this->GetRenderWindowPart(); if (renderWindowPart != nullptr) { QHash<QString, QmitkRenderWindow*> renderWindows = renderWindowPart->GetQmitkRenderWindows(); for(const auto& renderWindow : renderWindows.keys()) { m_Controls.propertyListComboBox->addItem(QString("Data node: ") + renderWindow); } } m_Controls.propertyListComboBox->addItem("Base data"); m_Controls.newButton->setEnabled(false); this->HideAllIcons(); m_ProxyModel = new QmitkPropertyItemSortFilterProxyModel(m_Controls.treeView); m_Model = new QmitkPropertyItemModel(m_ProxyModel); m_ProxyModel->setSourceModel(m_Model); m_ProxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_ProxyModel->setDynamicSortFilter(true); m_Delegate = new QmitkPropertyItemDelegate(m_Controls.treeView); m_Controls.singleSlot->SetDataStorage(GetDataStorage()); m_Controls.singleSlot->SetSelectionIsOptional(true); m_Controls.singleSlot->SetEmptyInfo(QString("Please select a data node")); m_Controls.singleSlot->SetPopUpTitel(QString("Select data node")); m_SelectionServiceConnector = std::make_unique<QmitkSelectionServiceConnector>(); SetAsSelectionListener(true); auto selection = this->GetSite()->GetWorkbenchWindow()->GetSelectionService()->GetSelection(); auto currentSelection = GetInitialSelection(selection); if (!currentSelection.isEmpty()) m_Controls.singleSlot->SetCurrentSelection(currentSelection); m_Controls.filterLineEdit->setClearButtonEnabled(true); m_Controls.treeView->setItemDelegateForColumn(1, m_Delegate); m_Controls.treeView->setModel(m_ProxyModel); m_Controls.treeView->setColumnWidth(0, 160); m_Controls.treeView->sortByColumn(0, Qt::AscendingOrder); m_Controls.treeView->setSelectionBehavior(QAbstractItemView::SelectRows); m_Controls.treeView->setSelectionMode(QAbstractItemView::SingleSelection); m_Controls.treeView->setEditTriggers(QAbstractItemView::SelectedClicked | QAbstractItemView::DoubleClicked); const int ICON_SIZE = 32; auto icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/tags.svg")); m_Controls.tagsLabel->setPixmap(icon.pixmap(ICON_SIZE)); icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/tag.svg")); m_Controls.tagLabel->setPixmap(icon.pixmap(ICON_SIZE)); icon = berry::QtStyleManager::ThemeIcon(QStringLiteral(":/org_mitk_icons/icons/awesome/scalable/actions/document-save.svg")); m_Controls.saveLabel->setPixmap(icon.pixmap(ICON_SIZE)); connect(m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::CurrentSelectionChanged, this, &QmitkPropertyTreeView::OnCurrentSelectionChanged); connect(m_Controls.filterLineEdit, &QLineEdit::textChanged, this, &QmitkPropertyTreeView::OnFilterTextChanged); connect(m_Controls.propertyListComboBox, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, &QmitkPropertyTreeView::OnPropertyListChanged); connect(m_Controls.newButton, &QPushButton::clicked, this, &QmitkPropertyTreeView::OnAddNewProperty); connect(m_Controls.treeView->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &QmitkPropertyTreeView::OnCurrentRowChanged); connect(m_Model, &QmitkPropertyItemModel::modelReset, this, &QmitkPropertyTreeView::OnModelReset); } void QmitkPropertyTreeView::SetAsSelectionListener(bool checked) { if (checked) { m_SelectionServiceConnector->AddPostSelectionListener(GetSite()->GetWorkbenchWindow()->GetSelectionService()); connect(m_SelectionServiceConnector.get(), &QmitkSelectionServiceConnector::ServiceSelectionChanged, m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::SetCurrentSelection); } else { m_SelectionServiceConnector->RemovePostSelectionListener(); disconnect(m_SelectionServiceConnector.get(), &QmitkSelectionServiceConnector::ServiceSelectionChanged, m_Controls.singleSlot, &QmitkSingleNodeSelectionWidget::SetCurrentSelection); } } QString QmitkPropertyTreeView::GetPropertyNameOrAlias(const QModelIndex& index) { QString propertyName; if (index.isValid()) { QModelIndex current = index; while (current.isValid()) { QString name = m_ProxyModel->data(m_ProxyModel->index(current.row(), 0, current.parent())).toString(); propertyName.prepend(propertyName.isEmpty() ? name : name.append('.')); current = current.parent(); } } return propertyName; } void QmitkPropertyTreeView::OnCurrentSelectionChanged(QList<mitk::DataNode::Pointer> nodes) { if (nodes.empty() || nodes.front().IsNull()) { m_SelectedNode = nullptr; this->SetPartName("Properties"); m_Model->SetPropertyList(nullptr); m_Delegate->SetPropertyList(nullptr); m_Controls.newButton->setEnabled(false); return; } // node is selected, create tree with node properties m_SelectedNode = nodes.front(); mitk::PropertyList* propertyList = m_Model->GetPropertyList(); if (m_Renderer == nullptr && m_Controls.propertyListComboBox->currentText() == "Base data") { propertyList = m_SelectedNode->GetData() != nullptr ? m_SelectedNode->GetData()->GetPropertyList() : nullptr; } else { propertyList = m_SelectedNode->GetPropertyList(m_Renderer); } QString selectionClassName = m_SelectedNode->GetData() != nullptr ? m_SelectedNode->GetData()->GetNameOfClass() : ""; m_SelectionClassName = selectionClassName.toStdString(); m_Model->SetPropertyList(propertyList, selectionClassName); m_Delegate->SetPropertyList(propertyList); m_Controls.newButton->setEnabled(true); if (!m_ProxyModel->filterRegExp().isEmpty()) { m_Controls.treeView->expandAll(); } } void QmitkPropertyTreeView::HideAllIcons() { m_Controls.tagLabel->hide(); m_Controls.tagsLabel->hide(); m_Controls.saveLabel->hide(); } void QmitkPropertyTreeView::OnCurrentRowChanged(const QModelIndex& current, const QModelIndex&) { if (current.isValid()) { QString name = this->GetPropertyNameOrAlias(current); if (!name.isEmpty()) { QString alias; bool isTrueName = true; std::string trueName = m_PropertyAliases->GetPropertyName(name.toStdString()); if (trueName.empty() && !m_SelectionClassName.empty()) trueName = m_PropertyAliases->GetPropertyName(name.toStdString(), m_SelectionClassName); if (!trueName.empty()) { alias = name; name = QString::fromStdString(trueName); isTrueName = false; } QString description = QString::fromStdString(m_PropertyDescriptions->GetDescription(name.toStdString())); std::vector<std::string> aliases; if (!isTrueName) { aliases = m_PropertyAliases->GetAliases(name.toStdString(), m_SelectionClassName); if (aliases.empty() && !m_SelectionClassName.empty()) aliases = m_PropertyAliases->GetAliases(name.toStdString()); } bool isPersistent = m_PropertyPersistence->HasInfo(name.toStdString()); if (!description.isEmpty() || !aliases.empty() || isPersistent) { QString customizedDescription; if (!aliases.empty()) { customizedDescription = "<h3 style=\"margin-bottom:0\">" + name + "</h3>"; std::size_t numAliases = aliases.size(); std::size_t lastAlias = numAliases - 1; for (std::size_t i = 0; i < numAliases; ++i) { customizedDescription += i != lastAlias ? "<h5 style=\"margin-top:0;margin-bottom:0\">" : "<h5 style=\"margin-top:0;margin-bottom:10px\">"; customizedDescription += QString::fromStdString(aliases[i]) + "</h5>"; } } else { customizedDescription = "<h3 style=\"margin-bottom:10px\">" + name + "</h3>"; } if (!description.isEmpty()) customizedDescription += "<p>" + description + "</p>"; m_Controls.tagsLabel->setVisible(!aliases.empty() && aliases.size() > 1); m_Controls.tagLabel->setVisible(!aliases.empty() && aliases.size() == 1); m_Controls.saveLabel->setVisible(isPersistent); m_Controls.descriptionLabel->setText(customizedDescription); m_Controls.descriptionLabel->show(); return; } } } m_Controls.descriptionLabel->hide(); this->HideAllIcons(); } void QmitkPropertyTreeView::OnPropertyListChanged(int index) { if (index == -1) return; QString renderer = m_Controls.propertyListComboBox->itemText(index); if (renderer.startsWith("Data node: ")) renderer = QString::fromStdString(renderer.toStdString().substr(11)); m_Renderer = nullptr; if (renderer != "common" && renderer != "Base data") { auto* renderWindowPart = this->GetRenderWindowPart(); if (nullptr != renderWindowPart) m_Renderer = renderWindowPart->GetQmitkRenderWindow(renderer)->GetRenderer(); } QList<mitk::DataNode::Pointer> nodes; if (m_SelectedNode.IsNotNull()) nodes << m_SelectedNode; this->OnCurrentSelectionChanged(nodes); } void QmitkPropertyTreeView::OnAddNewProperty() { std::unique_ptr<QmitkAddNewPropertyDialog> dialog(m_Controls.propertyListComboBox->currentText() != "Base data" ? new QmitkAddNewPropertyDialog(m_SelectedNode, m_Renderer) : new QmitkAddNewPropertyDialog(m_SelectedNode->GetData())); if (dialog->exec() == QDialog::Accepted) this->m_Model->Update(); } void QmitkPropertyTreeView::OnFilterTextChanged(const QString& filter) { m_ProxyModel->setFilterWildcard(filter); if (filter.isEmpty()) m_Controls.treeView->collapseAll(); else m_Controls.treeView->expandAll(); } void QmitkPropertyTreeView::OnModelReset() { m_Controls.descriptionLabel->hide(); this->HideAllIcons(); } <|endoftext|>
<commit_before>/* kopetexsl.cpp - Kopete XSL Routines Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <libxslt/xsltconfig.h> #include <libxslt/xsltInternals.h> #include <libxslt/transform.h> #include <libxml/parser.h> #include <kdebug.h> #include <kopetexsl.h> #include <qregexp.h> #include <qsignal.h> /** * @author Jason Keirstead <jason@keirstead.org> * * The thread class that actually performs the XSL processing. * Using a thread allows for async operation. */ class KopeteXSLThread : public QThread { public: /** * Thread constructor * * @param xmlString The XML to be transformed * @param xslString The XSL string we will use to transform * @param target Target object to connect to for async operation * @param slotCompleted Slot to fire on completion in asnc operation */ KopeteXSLThread( const QString &xmlString, const QString &xslString, QObject *target = 0L, const char* slotCompleted = 0L ); /** * Re implimented from QThread. Does the processing. */ virtual void run(); /** * Returns the result string */ const QString &result() { return m_resultString; }; private: QString m_xml; QString m_xsl; QString m_resultString; QObject *m_target; const char* m_slotCompleted; }; KopeteXSLThread::KopeteXSLThread( const QString &xmlString, const QString &xslString, QObject *target, const char* slotCompleted ) { m_xml = xmlString; m_xsl = xslString; m_target = target; m_slotCompleted = slotCompleted; } void KopeteXSLThread::run() { xsltStylesheetPtr style_sheet = NULL; xmlDocPtr xmlDoc, xslDoc, resultDoc; //Init Stuff xmlLoadExtDtdDefaultValue = 0; xmlSubstituteEntitiesDefault(1); // Convert QString into a C string QCString xmlCString = m_xml.utf8(); QCString xslCString = m_xsl.utf8(); // Read XML docs in from memory xmlDoc = xmlParseMemory( xmlCString, xmlCString.length() ); xslDoc = xmlParseMemory( xslCString, xslCString.length() ); if( xmlDoc != NULL ) { if( xslDoc != NULL ) { style_sheet = xsltParseStylesheetDoc( xslDoc ); if( style_sheet != NULL ) { resultDoc = xsltApplyStylesheet(style_sheet, xmlDoc, NULL); if( resultDoc != NULL ) { //Save the result into the QString xmlChar *mem; int size; xmlDocDumpMemory( resultDoc, &mem, &size ); m_resultString = QString::fromUtf8( QCString( (char*)mem, size + 1 ) ); delete mem; xmlFreeDoc(resultDoc); } else { kdDebug() << "Transformed document is null!!!" << endl; } xsltFreeStylesheet(style_sheet); } else { kdDebug() << "Document is not valid XSL!!!" << endl; xmlFreeDoc(xslDoc); } } else { kdDebug() << "XSL Document could not be parsed!!!" << endl; } xmlFreeDoc(xmlDoc); } else { kdDebug() << "XML Document could not be parsed!!!" << endl; } //Signal completion if( m_target && m_slotCompleted ) { QSignal completeSignal( m_target ); completeSignal.connect( m_target, m_slotCompleted ); completeSignal.setValue( m_resultString ); completeSignal.activate(); delete this; } } extern int xmlLoadExtDtdDefaultValue; const QString KopeteXSL::xsltTransform( const QString &xmlString, const QString &xslString ) { KopeteXSLThread mThread( xmlString, xslString ); mThread.start(); mThread.wait(); return mThread.result(); } void KopeteXSL::xsltTransformAsync( const QString &xmlString, const QString &xslString, QObject *target, const char* slotCompleted ) { KopeteXSLThread *mThread = new KopeteXSLThread( xmlString, xslString, target, slotCompleted ); mThread->start(); } bool KopeteXSL::isValid( const QString &xslString ) { xsltStylesheetPtr style_sheet = NULL; xmlDocPtr xslDoc = NULL; bool retVal = false; // Convert QString into a C string QCString xslCString = xslString.utf8(); xslDoc = xmlParseMemory( xslCString, xslCString.length() ); if( xslDoc != NULL ) { style_sheet = xsltParseStylesheetDoc( xslDoc ); if( style_sheet != NULL ) { retVal = true; xsltFreeStylesheet(style_sheet); } else { xmlFreeDoc(xslDoc); } } return retVal; } <commit_msg>Free not delete<commit_after>/* kopetexsl.cpp - Kopete XSL Routines Copyright (c) 2003 by Jason Keirstead <jason@keirstead.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include <libxslt/xsltconfig.h> #include <libxslt/xsltInternals.h> #include <libxslt/transform.h> #include <libxml/parser.h> #include <kdebug.h> #include <kopetexsl.h> #include <qregexp.h> #include <qsignal.h> /** * @author Jason Keirstead <jason@keirstead.org> * * The thread class that actually performs the XSL processing. * Using a thread allows for async operation. */ class KopeteXSLThread : public QThread { public: /** * Thread constructor * * @param xmlString The XML to be transformed * @param xslString The XSL string we will use to transform * @param target Target object to connect to for async operation * @param slotCompleted Slot to fire on completion in asnc operation */ KopeteXSLThread( const QString &xmlString, const QString &xslString, QObject *target = 0L, const char* slotCompleted = 0L ); /** * Re implimented from QThread. Does the processing. */ virtual void run(); /** * Returns the result string */ const QString &result() { return m_resultString; }; private: QString m_xml; QString m_xsl; QString m_resultString; QObject *m_target; const char* m_slotCompleted; }; KopeteXSLThread::KopeteXSLThread( const QString &xmlString, const QString &xslString, QObject *target, const char* slotCompleted ) { m_xml = xmlString; m_xsl = xslString; m_target = target; m_slotCompleted = slotCompleted; } void KopeteXSLThread::run() { xsltStylesheetPtr style_sheet = NULL; xmlDocPtr xmlDoc, xslDoc, resultDoc; //Init Stuff xmlLoadExtDtdDefaultValue = 0; xmlSubstituteEntitiesDefault(1); // Convert QString into a C string QCString xmlCString = m_xml.utf8(); QCString xslCString = m_xsl.utf8(); // Read XML docs in from memory xmlDoc = xmlParseMemory( xmlCString, xmlCString.length() ); xslDoc = xmlParseMemory( xslCString, xslCString.length() ); if( xmlDoc != NULL ) { if( xslDoc != NULL ) { style_sheet = xsltParseStylesheetDoc( xslDoc ); if( style_sheet != NULL ) { resultDoc = xsltApplyStylesheet(style_sheet, xmlDoc, NULL); if( resultDoc != NULL ) { //Save the result into the QString xmlChar *mem; int size; xmlDocDumpMemory( resultDoc, &mem, &size ); m_resultString = QString::fromUtf8( QCString( (char*)mem, size + 1 ) ); free(mem); xmlFreeDoc(resultDoc); } else { kdDebug() << "Transformed document is null!!!" << endl; } xsltFreeStylesheet(style_sheet); } else { kdDebug() << "Document is not valid XSL!!!" << endl; xmlFreeDoc(xslDoc); } } else { kdDebug() << "XSL Document could not be parsed!!!" << endl; } xmlFreeDoc(xmlDoc); } else { kdDebug() << "XML Document could not be parsed!!!" << endl; } //Signal completion if( m_target && m_slotCompleted ) { QSignal completeSignal( m_target ); completeSignal.connect( m_target, m_slotCompleted ); completeSignal.setValue( m_resultString ); completeSignal.activate(); delete this; } } extern int xmlLoadExtDtdDefaultValue; const QString KopeteXSL::xsltTransform( const QString &xmlString, const QString &xslString ) { KopeteXSLThread mThread( xmlString, xslString ); mThread.start(); mThread.wait(); return mThread.result(); } void KopeteXSL::xsltTransformAsync( const QString &xmlString, const QString &xslString, QObject *target, const char* slotCompleted ) { KopeteXSLThread *mThread = new KopeteXSLThread( xmlString, xslString, target, slotCompleted ); mThread->start(); } bool KopeteXSL::isValid( const QString &xslString ) { xsltStylesheetPtr style_sheet = NULL; xmlDocPtr xslDoc = NULL; bool retVal = false; // Convert QString into a C string QCString xslCString = xslString.utf8(); xslDoc = xmlParseMemory( xslCString, xslCString.length() ); if( xslDoc != NULL ) { style_sheet = xsltParseStylesheetDoc( xslDoc ); if( style_sheet != NULL ) { retVal = true; xsltFreeStylesheet(style_sheet); } else { xmlFreeDoc(xslDoc); } } return retVal; } <|endoftext|>
<commit_before>/*- * Copyright (C) 2008-2009 by Maxim Ignatenko * gelraen.ua@gmail.com * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in * * the documentation and/or other materials provided with the * * distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * 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. * * * $Id$ */ #include "defs.h" #include <iostream> #include <translator.h> #include <config.h> #include <dcclient.h> #include <ircclient.h> #include <sys/select.h> #include <unistd.h> #include <fcntl.h> #include "../config.h" #include <cstdlib> #include <cstdio> #include <fstream> #include <sys/stat.h> using namespace std; void usage(); void version(); bool writepid(const string& pidfile); int main(int argc,char *argv[]) { Config conf; Translator trans; IRCClient irc; DCClient dc; string conffile=CONFFILE; string pidfile; bool daemonize=true; string logfile; int loglevel; bool bloglevel=false; // specified in command line? if (argc==1) { usage(); return 0; } char ch; while((ch = getopt(argc, argv, "dc:l:L:p:h")) != -1) { switch (ch) { case 'd': daemonize=false; break; case 'c': conffile=optarg; break; case 'l': logfile=optarg; break; case 'L': bloglevel=true; loglevel=(int)strtol(optarg, (char **)NULL, 10); break; case 'p': pidfile=optarg; break; case 'h': case '?': default: usage(); return(0); } } if (!conf.ReadFromFile(conffile)) { LOG(log::error, "Failed to load config. Exiting", true); return 1; } LogLevel= bloglevel ? loglevel : conf.m_loglevel; if(!logfile.empty()) if(dup2(open(logfile.c_str(), O_APPEND | O_CREAT, S_IRWXU | S_IRWXG),2)==-1) LOG(log::warning, "Failed to open log file. Continue logging to old stderr", true); if (!logfile.empty()) { conf.m_sLogFile=logfile; } if (!pidfile.empty()) { conf.m_pidfile=pidfile; } if (daemonize) { if (daemon(0,0)==-1) // chdir to '/' and close fd's 0-2 { LOG(log::error, "daemon() failed, exiting", true); return 1; } } if (!conf.m_pidfile.empty()&&!writepid(conf.m_pidfile)) { LOG(log::error,"Unable to write pidfile", true); } if (!irc.setConfig(conf)) { LOG(log::error,"Incorrect config for IRC", true); return 1; } if (!dc.setConfig(conf)) { LOG(log::error,"Incorrect config for DC++", true); return 1; } string str; LOG(log::notice,"Connecting to IRC... "); if (!irc.Connect()) { LOG(log::error,"ERROR"); return 2; } else LOG(log::notice,"OK"); LOG(log::notice,"Connecting to DC++... "); if (!dc.Connect()) { LOG(log::error,"ERROR"); return 2; } else LOG(log::notice,"OK"); // now recreate config, cause DC hub may change our nickname conf=Config(irc.getConfig(),dc.getConfig()); if (!trans.setConfig(conf)) { LOG(log::error,"Incorrect config for Translator"); return 1; } fd_set rset; int max=0,t; for(;;) { // recreate rset FD_ZERO(&rset); t=irc.FdSet(rset); max=(t>max)?t:max; t=dc.FdSet(rset); max=(t>max)?t:max; select(max+1,&rset,NULL,NULL,NULL); while(irc.readCommand(str)) { if (trans.IRCtoDC(str,str)) { dc.writeCommand(str); } } if (!dc.isLoggedIn()) { LOG(log::warning, "DC++ connection closed. Trying to reconnect..."); dc.Connect(); } while(dc.readCommand(str)) { if (trans.DCtoIRC(str,str)) { irc.writeCommand(str); } } if (!irc.isLoggedIn()) { LOG(log::warning,"IRC connection closed. Trying to reconnect..."); irc.Connect(); } } return 0; } void usage() { version(); cout << endl; cout << "Options:" << endl; cout << " -h - show this help message" << endl; cout << " -c file - specify path to config file" << endl; cout << " -l file - override path to logfile specified in config" << endl; cout << " -L num - override loglevel" << endl; cout << " -p file - override path to pidfile specified in config" << endl; cout << " -d - do not go in background, all logging goes to stderr" << endl; cout << endl; } void version() { cout << PACKAGE << " " << VERSION << endl; } bool writepid(const string& pidfile) { ofstream pid(pidfile.c_str()); if (pid.bad()) return false; pid << getpid() << endl; return true; } <commit_msg>Reopen file at stderr only after successful daemon(3) call<commit_after>/*- * Copyright (C) 2008-2009 by Maxim Ignatenko * gelraen.ua@gmail.com * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in * * the documentation and/or other materials provided with the * * distribution. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * * 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. * * * $Id$ */ #include "defs.h" #include <iostream> #include <translator.h> #include <config.h> #include <dcclient.h> #include <ircclient.h> #include <sys/select.h> #include <unistd.h> #include <fcntl.h> #include "../config.h" #include <cstdlib> #include <cstdio> #include <fstream> #include <sys/stat.h> using namespace std; void usage(); void version(); bool writepid(const string& pidfile); int main(int argc,char *argv[]) { Config conf; Translator trans; IRCClient irc; DCClient dc; string conffile=CONFFILE; string pidfile; bool daemonize=true; string logfile; int loglevel; bool bloglevel=false; // specified in command line? if (argc==1) { usage(); return 0; } char ch; while((ch = getopt(argc, argv, "dc:l:L:p:h")) != -1) { switch (ch) { case 'd': daemonize=false; break; case 'c': conffile=optarg; break; case 'l': logfile=optarg; break; case 'L': bloglevel=true; loglevel=(int)strtol(optarg, (char **)NULL, 10); break; case 'p': pidfile=optarg; break; case 'h': case '?': default: usage(); return(0); } } if (!conf.ReadFromFile(conffile)) { LOG(log::error, "Failed to load config. Exiting", true); return 1; } LogLevel= bloglevel ? loglevel : conf.m_loglevel; if (!logfile.empty()) { conf.m_sLogFile=logfile; } if (!pidfile.empty()) { conf.m_pidfile=pidfile; } if (daemonize) { if (daemon(0,0)==-1) // chdir to '/' and close fd's 0-2 { LOG(log::error, "daemon() failed, exiting", true); return 1; } if (dup2(open(conf.m_sLogFile.c_str(), O_APPEND | O_CREAT, S_IRWXU | S_IRWXG),2)==-1) { LOG(log::warning, "Failed to open log file. Continue logging to stderr", true); } } if (!conf.m_pidfile.empty()&&!writepid(conf.m_pidfile)) { LOG(log::error,"Unable to write pidfile", true); } if (!irc.setConfig(conf)) { LOG(log::error,"Incorrect config for IRC", true); return 1; } if (!dc.setConfig(conf)) { LOG(log::error,"Incorrect config for DC++", true); return 1; } string str; LOG(log::notice,"Connecting to IRC... "); if (!irc.Connect()) { LOG(log::error,"ERROR"); return 2; } else LOG(log::notice,"OK"); LOG(log::notice,"Connecting to DC++... "); if (!dc.Connect()) { LOG(log::error,"ERROR"); return 2; } else LOG(log::notice,"OK"); // now recreate config, cause DC hub may change our nickname conf=Config(irc.getConfig(),dc.getConfig()); if (!trans.setConfig(conf)) { LOG(log::error,"Incorrect config for Translator"); return 1; } fd_set rset; int max=0,t; for(;;) { // recreate rset FD_ZERO(&rset); t=irc.FdSet(rset); max=(t>max)?t:max; t=dc.FdSet(rset); max=(t>max)?t:max; select(max+1,&rset,NULL,NULL,NULL); while(irc.readCommand(str)) { if (trans.IRCtoDC(str,str)) { dc.writeCommand(str); } } if (!dc.isLoggedIn()) { LOG(log::warning, "DC++ connection closed. Trying to reconnect..."); dc.Connect(); } while(dc.readCommand(str)) { if (trans.DCtoIRC(str,str)) { irc.writeCommand(str); } } if (!irc.isLoggedIn()) { LOG(log::warning,"IRC connection closed. Trying to reconnect..."); irc.Connect(); } } return 0; } void usage() { version(); cout << endl; cout << "Options:" << endl; cout << " -h - show this help message" << endl; cout << " -c file - specify path to config file" << endl; cout << " -l file - override path to logfile specified in config" << endl; cout << " -L num - override loglevel" << endl; cout << " -p file - override path to pidfile specified in config" << endl; cout << " -d - do not go in background, all logging goes to stderr" << endl; cout << endl; } void version() { cout << PACKAGE << " " << VERSION << endl; } bool writepid(const string& pidfile) { ofstream pid(pidfile.c_str()); if (pid.bad()) return false; pid << getpid() << endl; return true; } <|endoftext|>
<commit_before>#include <Refal2.h> using namespace Refal2; typedef std::vector<std::string> CFileNames; class CSourceFilesProcessor : private IErrorHandler { public: static CProgramPtr Compile( const CFileNames& fileNames ); static bool Check( const CFileNames& fileNames ); private: CScanner scanner; std::ifstream file; CSourceFilesProcessor( const CFileNames& fileNames ); CSourceFilesProcessor( const CSourceFilesProcessor& ); CSourceFilesProcessor& operator=( const CSourceFilesProcessor& ); void processFile( const std::string& fileName ); virtual void Error( const CError& error ); }; CProgramPtr CSourceFilesProcessor::Compile( const CFileNames& fileNames ) { CSourceFilesProcessor sourceFilesProcessor( fileNames ); return sourceFilesProcessor.scanner.BuildProgram(); } bool CSourceFilesProcessor::Check( const CFileNames& fileNames ) { CSourceFilesProcessor sourceFilesProcessor( fileNames ); return sourceFilesProcessor.scanner.CheckProgram(); } CSourceFilesProcessor::CSourceFilesProcessor( const CFileNames& fileNames ) { scanner.SetErrorHandler( this ); if( fileNames.empty() ) { for( char c; std::cin.get( c ); ) { scanner.AddChar( c ); } if( scanner.ErrorSeverity() != ES_FatalError ) { scanner.AddEndOfFile(); } } else { for( CFileNames::const_iterator fileName = fileNames.begin(); fileName != fileNames.end(); ++fileName ) { processFile( *fileName ); if( scanner.ErrorSeverity() == ES_FatalError ) { break; } } } } void CSourceFilesProcessor::processFile( const std::string& fileName ) { file.open( fileName ); if( file.good() ) { scanner.SetFileName( fileName ); for( char c; file.get( c ); ) { scanner.AddChar( c ); } if( scanner.ErrorSeverity() != ES_FatalError ) { scanner.AddEndOfFile(); } } else { std::cerr << UtilityName << ": " << fileName << ": No such file" << std::endl; } } void CSourceFilesProcessor::Error( const CError& error ) { std::cerr << error.UserMessage() << std::endl; if( error.Severity() == ES_FatalError ) { file.clear( std::ios_base::eofbit ); std::cin.clear( std::ios_base::eofbit ); } } const char* const ExecutionResultStrings[] = { "ok", "recognition impossible", "call empty function", "lost function label", "wrong argument of embedded function" }; const std::string SeparatorLine( 80, '-' ); int main( int argc, const char* argv[] ) { std::ios::sync_with_stdio( false ); CFileNames fileNames; for( int i = 1; i < argc; i++ ) { fileNames.push_back( argv[i] ); } CProgramPtr program = CSourceFilesProcessor::Compile( fileNames ); if( !static_cast<bool>( program ) ) { return 1; } CReceptaclePtr receptacle( new CReceptacle ); CUnitList fieldOfView; CUnitNode* errorNode; TExecutionResult result = COperationsExecuter::Run( program, receptacle, fieldOfView, errorNode ); std::cout << SeparatorLine << std::endl; std::cout << "Execution result: " << ExecutionResultStrings[result] << "." << std::endl; if( !fieldOfView.IsEmpty() ) { std::cout << "Field of view: " << std::endl; CProgramPrintHelper programPrintHelper( program ); //programPrintHelper.SetPrintLabelWithModule(); fieldOfView.HandyPrint( std::cout, programPrintHelper ); } if( !receptacle->IsEmpty() ) { if( !fieldOfView.IsEmpty() ) { std::cout << SeparatorLine << std::endl; } std::cout << "Receptacle: " << std::endl; CUnitList receptacleUnitList; receptacle->DigOutAll( receptacleUnitList ); CProgramPrintHelper programPrintHelper( program ); receptacleUnitList.HandyPrint( std::cout, programPrintHelper ); std::cout << std::endl; } return 0; } <commit_msg>add command line options<commit_after>#include <Refal2.h> using namespace Refal2; //----------------------------------------------------------------------------- // Constants const char* const UtilityName = "refal2"; //----------------------------------------------------------------------------- // CCommandLineOptions typedef std::vector<std::string> CFileNames; class CCommandLineOptions { public: CCommandLineOptions() { ResetDefaults(); } void ResetDefaults(); bool SetByCommandLineArguments( int numberOfArguments, const char* const arguments[] ); bool IsCheckOnly() const { return isCheckOnly; } void SetCheckOnly( bool _isCheckOnly = true ) { isCheckOnly = _isCheckOnly; } bool IsInfoOnly() const { return isInfoOnly; } void SetInfoOnly( bool _isInfoOnly = true ) { isInfoOnly = _isInfoOnly; } void ResetSourceFiles() { sourceFiles.clear(); } bool HasSourceFiles() const { return !sourceFiles.empty(); } CFileNames SourceFiles() const { return sourceFiles; } void AddSourceFile( const std::string& fileName ) { sourceFiles.push_back( fileName ); } private: bool isInfoOnly; bool optionsEnd; // if true program only parse and print found errors bool isCheckOnly; // *.ref files CFileNames sourceFiles; static bool isOption( const std::string& argument ); bool parseArgument( const std::string& argument ); static void printInvalidOption( const std::string& argument ); static void printHelp(); static void printVersion(); }; //----------------------------------------------------------------------------- void CCommandLineOptions::ResetDefaults() { SetInfoOnly( false ); SetCheckOnly( false ); ResetSourceFiles(); } bool CCommandLineOptions::SetByCommandLineArguments( int numberOfArguments, const char* const arguments[] ) { ResetDefaults(); optionsEnd = false; for( int i = 0; i < numberOfArguments; i++ ) { if( !parseArgument( arguments[i] ) ) { ResetDefaults(); return false; } if( IsInfoOnly() ) { break; } } return true; } bool CCommandLineOptions::isOption( const std::string& argument ) { return ( argument.length() >= 2 && argument.front() == '-' ); } bool CCommandLineOptions::parseArgument( const std::string& argument ) { if( !optionsEnd && isOption( argument ) ) { if( argument == "-c" || argument == "--check" ) { SetCheckOnly(); } else if( argument == "--help" ) { SetInfoOnly(); printHelp(); } else if( argument == "--version" ) { SetInfoOnly(); printVersion(); } else if( argument == "--" ) { optionsEnd = true; } else { printInvalidOption( argument ); return false; } } else if( !argument.empty() ) { AddSourceFile( argument ); } return true; } void CCommandLineOptions::printInvalidOption( const std::string& argument ) { std::cerr << UtilityName << ": invalid option `" << argument << "`" << std::endl << "Try `" << UtilityName << " --help` for more information." << std::endl; } void CCommandLineOptions::printHelp() { std::cout << "Usage: " << UtilityName << " [OPTION]... [FILE]..." << std::endl << std::endl << " -c, --check check source FILE(s) for errors and exit" << std::endl << " --help display this help and exit" << std::endl << " --version output version information and exit" << std::endl << std::endl << "Report bugs to <refal2@yandex.ru>." << std::endl; } void CCommandLineOptions::printVersion() { std::cout << "Written by Anton Todua." << std::endl << "Report bugs to <refal2@yandex.ru>" << std::endl; } //----------------------------------------------------------------------------- // CSourceFilesProcessor class CSourceFilesProcessor : private IErrorHandler { public: static CProgramPtr Compile( const CFileNames& fileNames ); static bool Check( const CFileNames& fileNames ); private: CScanner scanner; std::ifstream file; CSourceFilesProcessor( const CFileNames& fileNames ); CSourceFilesProcessor( const CSourceFilesProcessor& ); CSourceFilesProcessor& operator=( const CSourceFilesProcessor& ); void processFile( const std::string& fileName ); virtual void Error( const CError& error ); }; //----------------------------------------------------------------------------- CProgramPtr CSourceFilesProcessor::Compile( const CFileNames& fileNames ) { CSourceFilesProcessor sourceFilesProcessor( fileNames ); return sourceFilesProcessor.scanner.BuildProgram(); } bool CSourceFilesProcessor::Check( const CFileNames& fileNames ) { CSourceFilesProcessor sourceFilesProcessor( fileNames ); return sourceFilesProcessor.scanner.CheckProgram(); } CSourceFilesProcessor::CSourceFilesProcessor( const CFileNames& fileNames ) { scanner.SetErrorHandler( this ); if( fileNames.empty() ) { for( char c; std::cin.get( c ); ) { scanner.AddChar( c ); } if( scanner.ErrorSeverity() != ES_FatalError ) { scanner.AddEndOfFile(); } } else { for( CFileNames::const_iterator fileName = fileNames.begin(); fileName != fileNames.end(); ++fileName ) { processFile( *fileName ); if( scanner.ErrorSeverity() == ES_FatalError ) { break; } } } } void CSourceFilesProcessor::processFile( const std::string& fileName ) { file.open( fileName ); if( file.good() ) { scanner.SetFileName( fileName ); for( char c; file.get( c ); ) { scanner.AddChar( c ); } if( scanner.ErrorSeverity() != ES_FatalError ) { scanner.AddEndOfFile(); } } else { scanner.SetFileName( UtilityName ); scanner.RaiseError( ES_FatalError, "no such file" ); scanner.ResetFileName(); } } void CSourceFilesProcessor::Error( const CError& error ) { std::cerr << error.UserMessage() << std::endl; if( error.Severity() == ES_FatalError ) { file.clear( std::ios_base::eofbit ); std::cin.clear( std::ios_base::eofbit ); } } //----------------------------------------------------------------------------- const char* const ExecutionResultStrings[] = { "ok", "recognition impossible", "call empty function", "lost function label", "wrong argument of embedded function" }; const std::string SeparatorLine( 80, '-' ); int main( int argc, const char* argv[] ) { std::ios::sync_with_stdio( false ); CCommandLineOptions commandLineOptions; if( !commandLineOptions.SetByCommandLineArguments( argc - 1, argv + 1 ) ) { return 1; } if( commandLineOptions.IsInfoOnly() ) { return 0; } if( commandLineOptions.IsCheckOnly() ) { return ( CSourceFilesProcessor::Check( commandLineOptions.SourceFiles() ) ? 0 : 1 ); } CProgramPtr program = CSourceFilesProcessor::Compile( commandLineOptions.SourceFiles() ); if( !static_cast<bool>( program ) ) { return 1; } CReceptaclePtr receptacle( new CReceptacle ); CUnitList fieldOfView; CUnitNode* errorNode; TExecutionResult result = COperationsExecuter::Run( program, receptacle, fieldOfView, errorNode ); std::cout << SeparatorLine << std::endl; std::cout << "Execution result: " << ExecutionResultStrings[result] << "." << std::endl; if( !fieldOfView.IsEmpty() ) { std::cout << "Field of view: " << std::endl; CProgramPrintHelper programPrintHelper( program ); //programPrintHelper.SetPrintLabelWithModule(); fieldOfView.HandyPrint( std::cout, programPrintHelper ); } if( !receptacle->IsEmpty() ) { if( !fieldOfView.IsEmpty() ) { std::cout << SeparatorLine << std::endl; } std::cout << "Receptacle: " << std::endl; CUnitList receptacleUnitList; receptacle->DigOutAll( receptacleUnitList ); CProgramPrintHelper programPrintHelper( program ); receptacleUnitList.HandyPrint( std::cout, programPrintHelper ); std::cout << std::endl; } return 0; } <|endoftext|>
<commit_before>#include <logging/Logger.h> #include <graphics/GlfwContext.h> #include <graphics/GlfwWindow.h> #include <graphics/Renderer.h> #include <gamemodel/GameState.h> #include <input/Input.h> int main(int argc, char ** argv) { Logger::initSystem(argc, argv); GlfwContext glfwContext(Logger::glfwErrorCallback); GlfwWindow glfwWindow(1200, 800); GameState gameState; Input input(gameState); Renderer renderer(glfwWindow, gameState); glfwWindow.makeCurrent(); glfwWindow.setKeyCallback(input.handleKeyboardFcnPtr); glfwWindow.enterMainLoop([&] { const double t = glfwGetTime(); input.update(t); gameState.update(t); renderer.draw(t); return t < 5.0; }); return 0; } <commit_msg>empty commit to see if git email is linked properly<commit_after>#include <logging/Logger.h> #include <graphics/GlfwContext.h> #include <graphics/GlfwWindow.h> #include <graphics/Renderer.h> #include <gamemodel/GameState.h> #include <input/Input.h> int main(int argc, char ** argv) { Logger::initSystem(argc, argv); GlfwContext glfwContext(Logger::glfwErrorCallback); GlfwWindow glfwWindow(1200, 800); GameState gameState; Input input(gameState); Renderer renderer(glfwWindow, gameState); glfwWindow.makeCurrent(); glfwWindow.setKeyCallback(input.handleKeyboardFcnPtr); glfwWindow.enterMainLoop([&] { const double t = glfwGetTime(); input.update(t); gameState.update(t); renderer.draw(t); return t < 5.0; }); return 0; } <|endoftext|>
<commit_before>#include "global.hpp" using namespace std; static char* exe; static void usagemode() { printf( "Usage mode: %s <option>\n" "\n" "Options:\n" " install <new directory name without trailing slash>\n" " start\n" " stop\n" " restart (just a stop followed by a start)\n" " reload (reload all settings except webserver)\n" " rerun-id <attempt id>\n" " rerun-atts <list of problem names>\n" " rerun-all-atts [list of problem names to skip]\n", exe ); } int main(int argc, char** argv) { exe = argv[0]; if (argc == 1) { usagemode(); return 0; } string mode = argv[1]; if (mode == "install") { if (argc == 2) { usagemode(); return 0; } Global::install(argv[2]); } else if (mode == "start") { Global::start(); } else if (mode == "stop") { Global::stop(); } else if (mode == "restart") { Global::stop(); Global::start(); } else if (mode == "reload") { Global::reload(); } else usagemode(); return 0; } <commit_msg>Update usage mode<commit_after>#include "global.hpp" using namespace std; static char* exe; static void usagemode() { printf( "Usage mode: %s <option>\n" "\n" "Installation option:\n" " install <non-existing directory path>\n" "\n" "The following options must be executed inside a directory created with\n" "the 'install' option.\n" "\n" "Offline options:\n" " start\n" "\n" "Online options:\n" " stop\n" " restart (stop followed by start)\n" " reload (just reload all settings except webserver's)\n" " rerun-att <attempt id>\n" " rerun-probs <list of problem id ranges> (* reruns ALL attempts)\n" " Example to rerun problems 1, 3, 4 and 5: %s rerun-probs 1 3-5\n", exe,exe ); } int main(int argc, char** argv) { exe = argv[0]; if (argc == 1) { usagemode(); return 0; } string mode = argv[1]; if (mode == "install") { if (argc == 2) { usagemode(); return 0; } Global::install(argv[2]); } else if (mode == "start") { Global::start(); } else if (mode == "stop") { Global::stop(); } else if (mode == "restart") { Global::stop(); Global::start(); } else if (mode == "reload") { Global::reload(); } else usagemode(); return 0; } <|endoftext|>
<commit_before>#include <gst/gst.h> #include <glib.h> // Message handler callback static gboolean bus_call (GstBus *bus, GstMessage *msg, gpointer data) { GMainLoop *loop = (GMainLoop *) data; switch (GST_MESSAGE_TYPE (msg)) { case GST_MESSAGE_EOS: g_print ("End of stream\n"); g_main_loop_quit (loop); break; case GST_MESSAGE_ERROR: { gchar *debug; GError *error; gst_message_parse_error (msg, &error, &debug); g_free (debug); g_printerr ("Error: %s\n", error->message); g_error_free (error); g_main_loop_quit (loop); break; } default: break; } return TRUE; } int main (int argc, char *argv[]) { GMainLoop *loop; GstElement *pipeline, *source, *parser, *decoder, *conv, *sink; GstBus *bus; guint bus_watch_id; /* Initialisation */ gst_init (&argc, &argv); loop = g_main_loop_new (NULL, FALSE); /* Create gstreamer elements */ pipeline = gst_pipeline_new("mp3_player"); source = gst_element_factory_make ("filesrc", "file-source"); parser = gst_element_factory_make ("mpegaudioparse", "parser"); decoder = gst_element_factory_make ("mpg123audiodec", "auto-decoder"); conv = gst_element_factory_make ("audioconvert", "converter"); sink = gst_element_factory_make ("pulsesink", "audio-output"); if (!pipeline || !source || !parser || !decoder || !conv ||!sink) { g_printerr ("One element could not be created. Exiting.\n"); return -1; } /* Set up the pipeline */ /* we set the input filename to the source element */ g_object_set (G_OBJECT (source), "location", "../../media/music/Tours_-_01_-_Enthusiast.mp3", NULL); // Message handler bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); bus_watch_id = gst_bus_add_watch (bus, bus_call, loop); gst_object_unref (bus); // Add elements to pipeline gst_bin_add_many (GST_BIN(pipeline), source, parser, decoder, conv, sink, NULL); // Link the elements together gst_element_link_many(source, parser, decoder, conv, sink, NULL); // Set pipeline to playing g_print ("Now playing: %s\n", "default"); gst_element_set_state (pipeline, GST_STATE_PLAYING); // Loop g_print ("Running...\n"); g_main_loop_run (loop); // Deinitialization g_print ("Returned, stopping playback\n"); gst_element_set_state (pipeline, GST_STATE_NULL); g_print ("Deleting pipeline\n"); gst_object_unref (GST_OBJECT (pipeline)); g_source_remove (bus_watch_id); g_main_loop_unref (loop); return 0; } <commit_msg>Use custom main loop<commit_after>#include <gst/gst.h> #include <glib.h> int main (int argc, char *argv[]) { //GMainLoop *loop; bool terminate=false; GstMessage *msg; GstElement *pipeline, *source, *parser, *decoder, *conv, *sink; GstBus *bus; //guint bus_watch_id; /* Initialisation */ gst_init (&argc, &argv); //loop = g_main_loop_new (NULL, FALSE); /* Create gstreamer elements */ pipeline = gst_pipeline_new("mp3_player"); source = gst_element_factory_make ("filesrc", "file-source"); parser = gst_element_factory_make ("mpegaudioparse", "parser"); decoder = gst_element_factory_make ("mpg123audiodec", "auto-decoder"); conv = gst_element_factory_make ("audioconvert", "converter"); sink = gst_element_factory_make ("pulsesink", "audio-output"); if (!pipeline || !source || !parser || !decoder || !conv ||!sink) { g_printerr ("One element could not be created. Exiting.\n"); return -1; } /* Set up the pipeline */ /* we set the input filename to the source element */ g_object_set (G_OBJECT (source), "location", "../../media/music/Tours_-_01_-_Enthusiast.mp3", NULL); // Add elements to pipeline gst_bin_add_many (GST_BIN(pipeline), source, parser, decoder, conv, sink, NULL); // Link the elements together gst_element_link_many(source, parser, decoder, conv, sink, NULL); // Set pipeline to playing g_print ("Now playing: %s\n", "default"); gst_element_set_state (pipeline, GST_STATE_PLAYING); // Loop--------------------------------------------- g_print ("Running...\n"); bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); do { // Pop one by one msg = gst_bus_timed_pop (bus, GST_CLOCK_TIME_NONE); /* Parse message */ if (msg != NULL) { GError *err; gchar *debug_info; switch (GST_MESSAGE_TYPE (msg)) { case GST_MESSAGE_ERROR: gst_message_parse_error (msg, &err, &debug_info); g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message); g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none"); g_clear_error (&err); g_free (debug_info); terminate = true; break; case GST_MESSAGE_EOS: g_print ("End-Of-Stream reached.\n"); terminate = true; break; case GST_MESSAGE_STATE_CHANGED: /* We are only interested in state-changed messages from the pipeline */ if (GST_MESSAGE_SRC (msg) == GST_OBJECT (pipeline)) { GstState old_state, new_state, pending_state; gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state); g_print ("Pipeline state changed from %s to %s:\n", gst_element_state_get_name (old_state), gst_element_state_get_name (new_state)); } break; default: // Do not handle any other message g_printerr ("INFO: unhandled message\n"); break; } gst_message_unref (msg); } } while (!terminate); // Deinitialization g_print ("Returned, stopping playback\n"); gst_object_unref (bus); gst_element_set_state (pipeline, GST_STATE_NULL); g_print ("Deleting pipeline\n"); gst_object_unref (GST_OBJECT (pipeline)); return 0; } <|endoftext|>
<commit_before>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include <ctime> #include "qpp.h" #include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: Error class // TODO: change all for(s) to column major order // TODO: use .data() raw pointer instead of looping using namespace std; using namespace qpp; using namespace qpp::types; int myfunc(const cplx &z) { return std::abs(z); } //int main(int argc, char **argv) int main() { _init(); // std::cout << std::fixed; // use fixed format for nice formatting //// std::cout << std::scientific; // std::cout << std::setprecision(4); // only for fixed or scientific modes // // cout << "Starting qpp..." << endl; // // // MATLAB interface testing // cmat randu = rand_unitary(3); // cout << endl; // displn(randu); // // saveMATLAB<cplx>(randu, "/Users/vlad/tmp/test.mat", "randu", "w"); // cmat res = loadMATLAB<cplx>("/Users/vlad/tmp/test.mat", "randu"); // cout << endl; // displn(randu - res); // // // functor testing // auto lambda = [](const cplx& z)->int // { return abs(z);}; // // cmat mat1(3, 3); // mat1 << 1, -2.56, 335.2321, -4, 5.244, -6.1, 7, -8, 9. + 2.78 * ct::ii; // // cout << endl; // displn(mat1); // // cout << endl; // displn(fun<cmat, int>(mat1 * mat1, lambda)); // // cout << endl; // displn(fun(mat1 * mat1, myfunc)); // // // other functions // cout << endl; // cmat mat11 = mat1 * mat1; // displn(kron((cmat) (mat1 * mat1), cmat(mat1 * mat1))); // // mat11 = cmat::Random(3, 3); // mat11 = mat11 + adjoint(mat11); // cmat mat2(2, 2); // mat2 << 1, ct::ii, -ct::ii, 1; // // eigenvalue test // cout << endl << hevals<cmat>(mat11) << endl; // displn( // mat11 * hevects(mat11).col(0) // - (hevals(mat11)(0)) * hevects(mat11).col(0)); // // cout << endl << mat11 << endl << endl; // // cout << endl; // displn(transpose(mat11)); // cout << typeid(transpose(mat11)).name() << endl<<endl; // // displn(transpose(mat11 * mat11)); // cout << typeid(transpose(mat11*mat11)).name() << endl; // // cout<<endl; // displn(kron_list<cmat>({gt::X*gt::X,gt::X+gt::X})); // // cout<<endl; // displn(kron_pow(gt::X*gt::X,2)); // // cout<<endl; // displn(kron(gt::X*gt::X,gt::X+gt::X)); size_t N = 5000; cmat test = cmat::Random(N, N); // measure time taken clock_t start, end; double time; start = clock(); /* process starts here */ norm(reshape(test, 1, N * N)); /* process ends here */ end = clock(); time = (double) (end - start); cout << "It took me " << time << " clicks (" << ((float) time) / CLOCKS_PER_SEC << " seconds)."; cout << endl << "Exiting qpp..." << endl; } <commit_msg>commit<commit_after>/* * File: main.cpp * Author: vlad * * Created on December 12, 2013, 10:38 PM */ #include <iostream> #include <ctime> #include "qpp.h" //#include "matlab.h" // support for MATLAB // TODO: expandout function // TODO: dyad function // TODO: proj (dya) function // TODO: ip (inner product function) function, make it general to return matrices // TODO: Error class // TODO: change all for(s) to column major order // TODO: use .data() raw pointer instead of looping using namespace std; using namespace qpp; using namespace qpp::types; int myfunc(const cplx &z) { return std::abs(z); } //int main(int argc, char **argv) int main() { _init(); std::cout << std::fixed; // use fixed format for nice formatting // std::cout << std::scientific; std::cout << std::setprecision(4); // only for fixed or scientific modes cout << "Starting qpp..." << endl; // MATLAB interface testing cmat randu = rand_unitary(3); cout << endl; displn(randu); //saveMATLAB<cplx>(randu, "/Users/vlad/tmp/test.mat", "randu", "w"); //cmat res = loadMATLAB<cplx>("/Users/vlad/tmp/test.mat", "randu"); cout << endl; //displn(randu - res); // functor testing auto lambda = [](const cplx& z)->int { return abs(z);}; cmat mat1(3, 3); mat1 << 1, -2.56, 335.2321, -4, 5.244, -6.1, 7, -8, 9. + 2.78 * ct::ii; cout << endl; displn(mat1); cout << endl; displn(fun<cmat, int>(mat1 * mat1, lambda)); cout << endl; displn(fun(mat1 * mat1, myfunc)); // other functions cout << endl; cmat mat11 = mat1 * mat1; displn(kron((cmat) (mat1 * mat1), cmat(mat1 * mat1))); mat11 = cmat::Random(3, 3); mat11 = mat11 + adjoint(mat11); cmat mat2(2, 2); mat2 << 1, ct::ii, -ct::ii, 1; // eigenvalue test cout << endl << hevals<cmat>(mat11) << endl; displn( mat11 * hevects(mat11).col(0) - (hevals(mat11)(0)) * hevects(mat11).col(0)); cout << endl << mat11 << endl << endl; cout << endl; displn(transpose(mat11)); cout << typeid(transpose(mat11)).name() << endl << endl; displn(transpose(mat11 * mat11)); cout << typeid(transpose(mat11 * mat11)).name() << endl; cout << endl; displn(kron_list<cmat>( { gt::X * gt::X, gt::X + gt::X })); cout << endl; displn(kron_pow(gt::X * gt::X, 2)); cout << endl; displn(kron(gt::X * gt::X, gt::X + gt::X)); size_t N = 5000; cmat test = cmat::Random(N, N); // measure time taken clock_t start, end; double time; start = clock(); /* process starts here */ norm(reshape(test, 1, N * N)); /* process ends here */ end = clock(); time = (double) (end - start); cout << "It took me " << time << " clicks (" << ((float) time) / CLOCKS_PER_SEC << " seconds)."; cout << endl << "Exiting qpp..." << endl; } <|endoftext|>
<commit_before>#include "System.h" #include "Display.h" #include "interface.h" #include "ecg.h" #include "nibp.h" #define DISPLAY_CS PC4 #define DISPLAY_RESET PC5 #define DISPLAY_SPI spi_c1 #define SCREEN_ROWS 10 #define SCREEN_COLUMNS 10 SPI_Interface display_spi(DISPLAY_SPI); Display tft(DISPLAY_CS, DISPLAY_RESET, &display_spi, SCREEN_ROWS, SCREEN_COLUMNS); int currentMode = 0; // Change mode Console c(USART2, 115200); /* Build UI Buttons */ Button settings = Button(9,9,2,2,RA8875_RED,"Alarm Settings",true,&tft); Button record = Button(5,9,2,2,RA8875_BLUE,"Data to Serial",true,&tft); Button confirm_button = Button(9,1,2,2,RA8875_GREEN,"Confirm",true,&tft); Button cancel_button = Button(9,9,2,2,RA8875_RED,"Cancel",true,&tft); Button default_button = Button(6,7,2,2,RA8875_LIGHTGREY,"Default Settings",true,&tft); ECGReadout ecg = ECGReadout(2,1,3,7,PB0,RA8875_BLUE,RA8875_LIGHTGREY,1000,tim3,&tft); TextBox title = TextBox(1,3,1,3,RA8875_BLACK,RA8875_WHITE,3,true,false,"FreePulse Patient Monitor v0.9", &tft); TextBox hr_label = TextBox(2,8,3,3,RA8875_BLACK,RA8875_BLUE,2,true,true,"BPM", &tft); LargeNumberView heartrate = LargeNumberView(3,8,2,3,RA8875_BLACK,RA8875_BLUE,true,60,&tft); Console c(USART2, 115200); extern "C" void TIM3_IRQHandler(void) { if (TIM_GetITStatus (TIM3, TIM_IT_Update) != RESET) { TIM_ClearITPendingBit(TIM3, TIM_IT_Update); int val = ecg.read(); c.print(val); c.print("\n"); } } void MainScreenInit(void){ tft.fillScreen(RA8875_BLACK); tft.showGrid(); title.draw(); settings.draw(); ecg.draw(); heartrate.draw(); hr_label.draw(); } void SettingsScreenInit(void){ tft.fillScreen(RA8875_BLACK); tft.showGrid(); confirm_button.draw(); default_button.draw(); cancel_button.draw(); } enum layout{ home, alarms }; void systemInit() { adcInit(); tft.startup(); ecg.enable(); } int main(void) { c.configure(); c.print("\n"); c.print("Starting FreePulse...\n"); layout currentMode = home; systemInit(); c.print("Welcome!\n"); while (1) { MainScreenInit(); delay(1000); tft.read_touch(); tft.reset_touch(); while (currentMode == home) { while (digitalRead(tft.interrupt)){ ecg.display_signal(); delay(100); } tft.read_touch(); if (settings.isTapped()){ tft.fillScreen(RA8875_BLACK); currentMode = alarms; } tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE); } if (currentMode == alarms) { SettingsScreenInit(); delay(1000); tft.read_touch(); tft.reset_touch(); while (currentMode == alarms) { while (digitalRead(tft.interrupt)){} tft.read_touch(); tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE); if (cancel_button.isTapped()) { tft.fillScreen(RA8875_BLACK); currentMode = home; } } } } return 0; } <commit_msg>Remove stray code from NIBP<commit_after>#include "System.h" #include "Display.h" #include "interface.h" #include "ecg.h" #define DISPLAY_CS PC4 #define DISPLAY_RESET PC5 #define DISPLAY_SPI spi_c1 #define SCREEN_ROWS 10 #define SCREEN_COLUMNS 10 SPI_Interface display_spi(DISPLAY_SPI); Display tft(DISPLAY_CS, DISPLAY_RESET, &display_spi, SCREEN_ROWS, SCREEN_COLUMNS); int currentMode = 0; // Change mode Console c(USART2, 115200); /* Build UI Buttons */ Button settings = Button(9,9,2,2,RA8875_RED,"Alarm Settings",true,&tft); Button record = Button(5,9,2,2,RA8875_BLUE,"Data to Serial",true,&tft); Button confirm_button = Button(9,1,2,2,RA8875_GREEN,"Confirm",true,&tft); Button cancel_button = Button(9,9,2,2,RA8875_RED,"Cancel",true,&tft); Button default_button = Button(6,7,2,2,RA8875_LIGHTGREY,"Default Settings",true,&tft); ECGReadout ecg = ECGReadout(2,1,3,7,PB0,RA8875_BLUE,RA8875_LIGHTGREY,1000,tim3,&tft); TextBox title = TextBox(1,3,1,3,RA8875_BLACK,RA8875_WHITE,3,true,false,"FreePulse Patient Monitor v0.9", &tft); TextBox hr_label = TextBox(2,8,3,3,RA8875_BLACK,RA8875_BLUE,2,true,true,"BPM", &tft); LargeNumberView heartrate = LargeNumberView(3,8,2,3,RA8875_BLACK,RA8875_BLUE,true,60,&tft); extern "C" void TIM3_IRQHandler(void) { if (TIM_GetITStatus (TIM3, TIM_IT_Update) != RESET) { TIM_ClearITPendingBit(TIM3, TIM_IT_Update); int val = ecg.read(); c.print(val); c.print("\n"); } } void MainScreenInit(void){ tft.fillScreen(RA8875_BLACK); tft.showGrid(); title.draw(); settings.draw(); ecg.draw(); heartrate.draw(); hr_label.draw(); } void SettingsScreenInit(void){ tft.fillScreen(RA8875_BLACK); tft.showGrid(); confirm_button.draw(); default_button.draw(); cancel_button.draw(); } enum layout{ home, alarms }; void systemInit() { adcInit(); tft.startup(); ecg.enable(); } int main(void) { c.configure(); c.print("\n"); c.print("Starting FreePulse...\n"); layout currentMode = home; systemInit(); c.print("Welcome!\n"); while (1) { MainScreenInit(); delay(1000); tft.read_touch(); tft.reset_touch(); while (currentMode == home) { while (digitalRead(tft.interrupt)){ ecg.display_signal(); delay(100); } tft.read_touch(); if (settings.isTapped()){ tft.fillScreen(RA8875_BLACK); currentMode = alarms; } tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE); } if (currentMode == alarms) { SettingsScreenInit(); delay(1000); tft.read_touch(); tft.reset_touch(); while (currentMode == alarms) { while (digitalRead(tft.interrupt)){} tft.read_touch(); tft.drawPixel(tft.touch_points[0],tft.touch_points[1], RA8875_WHITE); if (cancel_button.isTapped()) { tft.fillScreen(RA8875_BLACK); currentMode = home; } } } } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <mutex> #include <queue> #include <thread> #include <tuple> #include <condition_variable> #include "input_file_reader.hpp" #include "minimize.hpp" #include "comparator.hpp" #include "result.hpp" // mutex for shared resources static std::mutex g_tasks_mutex; // conditonal variable for shared resources static std::condition_variable g_cv; // global queue with two pointers to the sequences // they are compared directly if the both sequence lengths are small enough static std::queue<std::tuple<OLC::Sequence*, OLC::Sequence*>> g_sequence_pairs; // global queue with two pointers to vectors of minimizers // we use this instead if the sequences are too long static std::queue<std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*>> g_minimizer_pairs; static void worker() { // Get the task and remove it from the pool g_tasks_mutex.lock(); const std::tuple<OLC::Sequence*, OLC::Sequence*> sequence_pair = g_sequence_pairs.front(); g_sequence_pairs.pop(); const std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*> minimizer_pair = g_minimizer_pairs.front(); g_minimizer_pairs.pop(); g_tasks_mutex.unlock(); // Get the task sequences const OLC::Sequence* sequence1 = std::get<0>(sequence_pair); const OLC::Sequence* sequence2 = std::get<1>(sequence_pair); // Pull out the wrapped nucleotide vectors const std::vector<OLC::Nucleotide> nucleotides1 = sequence1->getNucleotides()->getSequence(); const std::vector<OLC::Nucleotide> nucleotides2 = sequence2->getNucleotides()->getSequence(); // If small enough, no need to use minimizers if (nucleotides1.size() < 20000 && nucleotides2.size() < 20000) { const OLC::Overlap overlap = compare(nucleotides1, nucleotides2); const uint32_t overlapFirstEnd = overlap.getEndFirst(); const uint32_t overlapSecondEnd = overlap.getEndSecond(); const uint32_t overlapFirstStart = overlap.getStartFirst(); const uint32_t overlapSecondStart = overlap.getStartSecond(); const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1; const std::string sequence1_ident = sequence1->getIdentifier(); const std::string sequence2_ident = sequence2->getIdentifier(); int32_t ahang = overlapFirstStart; int32_t bhang = nucleotides2.size() - overlapSecondEnd; if (overlapSecondStart > overlapFirstStart) { ahang *= -1; } if (nucleotides1.size() > overlapSecondEnd) { bhang *= -1; } //TODO: Add into result queue const OLC::Result result(sequence1_ident, sequence2_ident, overlapLength, ahang, bhang); } else { } return; } int main(int argc, char** argv) { std::ios_base::sync_with_stdio(false); if (argc != 3) { std::cout << "Usage: " << argv[0] << " <minimum overlap length L> <FASTQ or FASTA file>\n"; return 1; } // file with the data const std::string file = std::string(argv[2]); // L is the minimum overlap length const uint32_t L = std::stoi(argv[1]); // window size const uint32_t w = (L + 1) / 2; // size of the k-mer const uint32_t k = (L + 1) / 2; // read phase OLC::InputFileReader reader(file); const std::vector<OLC::Sequence*> sequences = reader.readSequences(); std::vector<std::vector<OLC::Minimizer>> minimizers; for (size_t i = 0; i < sequences.size(); ++i) { const auto sequence = sequences[i]->getNucleotides()->getSequence(); // calculate minimizers - both interior and end minimizers minimizers.push_back(minimize(sequence, w, k)); } // generate tasks so we can do this in parallel if possible std::queue<std::tuple<uint32_t, uint32_t>> tasks; for (uint32_t i = 0; i < sequences.size(); ++i) { for (uint32_t j = i + 1; j < sequences.size(); ++j) { g_sequence_pairs.emplace(sequences[i], sequences[j]); g_minimizer_pairs.emplace(&minimizers[i], &minimizers[j]); } } // use concurrent minimizer matching std::vector<std::thread> threads(std::thread::hardware_concurrency()); for (uint8_t i = 0; i < threads.size(); ++i) threads[i] = std::thread(worker); for (uint8_t i = 0; i < threads.size(); ++i) threads[i].join(); // cleanup for (size_t i = 0; i < sequences.size(); ++i) delete sequences[i]; return 0; } <commit_msg>main: do the simple case<commit_after>#include <iostream> #include <mutex> #include <queue> #include <thread> #include <tuple> #include <condition_variable> #include "input_file_reader.hpp" #include "minimize.hpp" #include "comparator.hpp" #include "result.hpp" // mutex for shared resources static std::mutex g_resource_mutex; // mutex for result vector static std::mutex g_result_mutex; // conditonal variable for shared resources static std::condition_variable g_resource_cv; // conditonal variable for result vector static std::condition_variable g_result_cv; // global queue with two pointers to the sequences // they are compared directly if the both sequence lengths are small enough static std::queue<std::tuple<OLC::Sequence*, OLC::Sequence*>> g_sequence_pairs; // global queue with two pointers to vectors of minimizers // we use this instead if the sequences are too long static std::queue<std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*>> g_minimizer_pairs; static std::vector<OLC::Result> g_results; static void worker() { while(true) { // Get the task and remove it from the pool std::unique_lock<std::mutex> resource_lock(g_resource_mutex); g_resource_cv.wait(resource_lock); if (g_sequence_pairs.empty()) return; const std::tuple<OLC::Sequence*, OLC::Sequence*> sequence_pair = g_sequence_pairs.front(); g_sequence_pairs.pop(); const std::tuple<std::vector<OLC::Minimizer>*, std::vector<OLC::Minimizer>*> minimizer_pair = g_minimizer_pairs.front(); g_minimizer_pairs.pop(); resource_lock.unlock(); g_resource_cv.notify_one(); // Get the task sequences const OLC::Sequence* sequence1 = std::get<0>(sequence_pair); const OLC::Sequence* sequence2 = std::get<1>(sequence_pair); // Pull out the wrapped nucleotide vectors const std::vector<OLC::Nucleotide> nucleotides1 = sequence1->getNucleotides()->getSequence(); const std::vector<OLC::Nucleotide> nucleotides2 = sequence2->getNucleotides()->getSequence(); // If small enough, no need to use minimizers if (nucleotides1.size() < 20000 && nucleotides2.size() < 20000) { const OLC::Overlap overlap = compare(nucleotides1, nucleotides2); const uint32_t overlapFirstEnd = overlap.getEndFirst(); const uint32_t overlapSecondEnd = overlap.getEndSecond(); const uint32_t overlapFirstStart = overlap.getStartFirst(); const uint32_t overlapSecondStart = overlap.getStartSecond(); const uint32_t overlapLength = overlapFirstEnd - overlapFirstStart + 1; const std::string sequence1_ident = sequence1->getIdentifier(); const std::string sequence2_ident = sequence2->getIdentifier(); int32_t ahang = overlapFirstStart; int32_t bhang = nucleotides2.size() - overlapSecondEnd; if (overlapSecondStart > overlapFirstStart) ahang *= -1; if (nucleotides1.size() > overlapSecondEnd) bhang *= -1; const OLC::Result result(sequence1_ident, sequence2_ident, overlapLength, ahang, bhang); std::unique_lock<std::mutex> result_lock(g_result_mutex); g_result_cv.wait(result_lock); g_results.push_back(result); result_lock.unlock(); g_result_cv.notify_one(); } else { } } } int main(int argc, char** argv) { std::ios_base::sync_with_stdio(false); if (argc != 3) { std::cout << "Usage: " << argv[0] << " <minimum overlap length L> <FASTQ or FASTA file>\n"; return 1; } // file with the data const std::string file = std::string(argv[2]); // L is the minimum overlap length const uint32_t L = std::stoi(argv[1]); // window size const uint32_t w = (L + 1) / 2; // size of the k-mer const uint32_t k = (L + 1) / 2; // read phase OLC::InputFileReader reader(file); const std::vector<OLC::Sequence*> sequences = reader.readSequences(); std::vector<std::vector<OLC::Minimizer>> minimizers; for (size_t i = 0; i < sequences.size(); ++i) { const auto sequence = sequences[i]->getNucleotides()->getSequence(); // calculate minimizers - both interior and end minimizers minimizers.push_back(minimize(sequence, w, k)); } // generate tasks so we can do this in parallel if possible std::queue<std::tuple<uint32_t, uint32_t>> tasks; for (uint32_t i = 0; i < sequences.size(); ++i) { for (uint32_t j = i + 1; j < sequences.size(); ++j) { g_sequence_pairs.emplace(sequences[i], sequences[j]); g_minimizer_pairs.emplace(&minimizers[i], &minimizers[j]); } } // use concurrent minimizer matching std::vector<std::thread> threads(std::thread::hardware_concurrency()); for (uint8_t i = 0; i < threads.size(); ++i) threads[i] = std::thread(worker); for (uint8_t i = 0; i < threads.size(); ++i) threads[i].join(); // cleanup for (size_t i = 0; i < sequences.size(); ++i) delete sequences[i]; return 0; } <|endoftext|>
<commit_before>/* * <<<<<<< HEAD * Copyright 2013 Mario Alviano, Carmine Dodaro and Francesco Ricca. ======= * Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca. >>>>>>> 5fc82930c51bc47fa41e640f5f2e1612ac22a801 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <cstdlib> #include "WaspFacade.h" #include "Options.h" using namespace std; int EXIT_CODE = 0; /* * */ int main( int argc, char** argv ) { wasp::Options::parse( argc, argv ); WaspFacade waspFacade; wasp::Options::setOptions( waspFacade ); waspFacade.readInput(); waspFacade.solve(); return EXIT_CODE; } <commit_msg>Removed a conflict in a comment.<commit_after>/* * * Copyright 2013 Mario Alviano, Carmine Dodaro, and Francesco Ricca. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <cstdlib> #include "WaspFacade.h" #include "Options.h" using namespace std; int EXIT_CODE = 0; /* * */ int main( int argc, char** argv ) { wasp::Options::parse( argc, argv ); WaspFacade waspFacade; wasp::Options::setOptions( waspFacade ); waspFacade.readInput(); waspFacade.solve(); return EXIT_CODE; } <|endoftext|>
<commit_before>// ImGui - standalone example application for DirectX 9 // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. #include "BoardView.h" #include "imgui_impl_dx9.h" #include <d3d9.h> #define DIRECTINPUT_VERSION 0x0800 #include <dinput.h> #include <tchar.h> #include "crtdbg.h" #include "platform.h" // Data static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; static D3DPRESENT_PARAMETERS g_d3dpp; extern LRESULT ImGui_ImplDX9_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplDX9_WndProcHandler(hWnd, msg, wParam, lParam)) return true; switch (msg) { case WM_SIZE: if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) { ImGui_ImplDX9_InvalidateDeviceObjects(); g_d3dpp.BackBufferWidth = LOWORD(lParam); g_d3dpp.BackBufferHeight = HIWORD(lParam); HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp); if (hr == D3DERR_INVALIDCALL) IM_ASSERT(0); ImGui_ImplDX9_CreateDeviceObjects(); } return 0; case WM_SYSCOMMAND: if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu return 0; break; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wParam, lParam); } int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Initialize comctl CoInitializeEx(NULL, COINIT_MULTITHREADED); static const wchar_t *class_name = L"ImGui Example"; // Create application window HINSTANCE instance = GetModuleHandle(NULL); HICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1)); WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, instance, icon, NULL, NULL, NULL, class_name, NULL}; RegisterClassEx(&wc); HWND hwnd = CreateWindow(class_name, _T("Open Board Viewer"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 1280, 800, NULL, NULL, wc.hInstance, NULL); // Initialize Direct3D LPDIRECT3D9 pD3D; if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) { UnregisterClass(class_name, wc.hInstance); MessageBox(hwnd, L"Failed to initialise Direct3D", NULL, 0); return 0; } ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); g_d3dpp.Windowed = TRUE; g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; g_d3dpp.EnableAutoDepthStencil = TRUE; g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Create the D3DDevice if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) { pD3D->Release(); UnregisterClass(class_name, wc.hInstance); MessageBox(hwnd, L"Failed to create Direct3D device", NULL, 0); return 0; } // Setup ImGui binding ImGui_ImplDX9_Init(hwnd, g_pd3dDevice); // Load Fonts // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt // for more details) ImGuiIO &io = ImGui::GetIO(); int ttf_size; unsigned char *ttf_data = LoadAsset(&ttf_size, ASSET_FIRA_SANS); ImFontConfig font_cfg{}; font_cfg.FontDataOwnedByAtlas = false; io.Fonts->AddFontFromMemoryTTF(ttf_data, ttf_size, 20.0f, &font_cfg); // io.Fonts->AddFontDefault(); // io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f); // io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f); // io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f); // io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f); // io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, // io.Fonts->GetGlyphRangesJapanese()); #if 0 // Get current flag int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Turn on leak-checking bit. tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF; // Set flag to the new value. _CrtSetDbgFlag(tmpFlag); #endif BoardView app{}; bool show_test_window = true; bool show_another_window = false; ImVec4 clear_col = ImColor(20, 20, 30); // Main loop MSG msg; ZeroMemory(&msg, sizeof(msg)); ShowWindow(hwnd, SW_SHOWDEFAULT); UpdateWindow(hwnd); while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); continue; } ImGui_ImplDX9_NewFrame(); #if 0 // 1. Show a simple window // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window // automatically called "Debug" { static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", (float *)&clear_col); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } // 2. Show another simple window, this time using an explicit Begin/End pair if (show_another_window) { ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver); ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello"); ImGui::End(); } #endif #if 0 // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow() if (show_test_window) { ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver); ImGui::ShowTestWindow(&show_test_window); } #endif app.Update(); if (app.m_wantsQuit) { PostMessage(hwnd, WM_QUIT, 0, 0); } // Rendering g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false); D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_col.x * 255.0f), (int)(clear_col.y * 255.0f), (int)(clear_col.z * 255.0f), (int)(clear_col.w * 255.0f)); g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); if (g_pd3dDevice->BeginScene() >= 0) { ImGui::Render(); g_pd3dDevice->EndScene(); } g_pd3dDevice->Present(NULL, NULL, NULL, NULL); } ImGui_ImplDX9_Shutdown(); if (g_pd3dDevice) g_pd3dDevice->Release(); if (pD3D) pD3D->Release(); UnregisterClass(class_name, wc.hInstance); return 0; } <commit_msg>Revert "Display an error when DirectX can't be initialised"<commit_after>// ImGui - standalone example application for DirectX 9 // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. #include "BoardView.h" #include "imgui_impl_dx9.h" #include <d3d9.h> #define DIRECTINPUT_VERSION 0x0800 #include <dinput.h> #include <tchar.h> #include "crtdbg.h" #include "platform.h" // Data static LPDIRECT3DDEVICE9 g_pd3dDevice = NULL; static D3DPRESENT_PARAMETERS g_d3dpp; extern LRESULT ImGui_ImplDX9_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui_ImplDX9_WndProcHandler(hWnd, msg, wParam, lParam)) return true; switch (msg) { case WM_SIZE: if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED) { ImGui_ImplDX9_InvalidateDeviceObjects(); g_d3dpp.BackBufferWidth = LOWORD(lParam); g_d3dpp.BackBufferHeight = HIWORD(lParam); HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp); if (hr == D3DERR_INVALIDCALL) IM_ASSERT(0); ImGui_ImplDX9_CreateDeviceObjects(); } return 0; case WM_SYSCOMMAND: if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu return 0; break; case WM_DESTROY: PostQuitMessage(0); return 0; } return DefWindowProc(hWnd, msg, wParam, lParam); } int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { // Initialize comctl CoInitializeEx(NULL, COINIT_MULTITHREADED); static const wchar_t *class_name = L"ImGui Example"; // Create application window HINSTANCE instance = GetModuleHandle(NULL); HICON icon = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1)); WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, instance, icon, NULL, NULL, NULL, class_name, NULL}; RegisterClassEx(&wc); HWND hwnd = CreateWindow(class_name, _T("Open Board Viewer"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 1280, 800, NULL, NULL, wc.hInstance, NULL); // Initialize Direct3D LPDIRECT3D9 pD3D; if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL) { UnregisterClass(class_name, wc.hInstance); return 0; } ZeroMemory(&g_d3dpp, sizeof(g_d3dpp)); g_d3dpp.Windowed = TRUE; g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; g_d3dpp.EnableAutoDepthStencil = TRUE; g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16; g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Create the D3DDevice if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0) { pD3D->Release(); UnregisterClass(class_name, wc.hInstance); return 0; } // Setup ImGui binding ImGui_ImplDX9_Init(hwnd, g_pd3dDevice); // Load Fonts // (there is a default font, this is only if you want to change it. see extra_fonts/README.txt // for more details) ImGuiIO &io = ImGui::GetIO(); int ttf_size; unsigned char *ttf_data = LoadAsset(&ttf_size, ASSET_FIRA_SANS); ImFontConfig font_cfg{}; font_cfg.FontDataOwnedByAtlas = false; io.Fonts->AddFontFromMemoryTTF(ttf_data, ttf_size, 20.0f, &font_cfg); // io.Fonts->AddFontDefault(); // io.Fonts->AddFontFromFileTTF("../../extra_fonts/Cousine-Regular.ttf", 15.0f); // io.Fonts->AddFontFromFileTTF("../../extra_fonts/DroidSans.ttf", 16.0f); // io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyClean.ttf", 13.0f); // io.Fonts->AddFontFromFileTTF("../../extra_fonts/ProggyTiny.ttf", 10.0f); // io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, // io.Fonts->GetGlyphRangesJapanese()); #if 0 // Get current flag int tmpFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); // Turn on leak-checking bit. tmpFlag |= _CRTDBG_CHECK_ALWAYS_DF; // Set flag to the new value. _CrtSetDbgFlag(tmpFlag); #endif BoardView app{}; bool show_test_window = true; bool show_another_window = false; ImVec4 clear_col = ImColor(20, 20, 30); // Main loop MSG msg; ZeroMemory(&msg, sizeof(msg)); ShowWindow(hwnd, SW_SHOWDEFAULT); UpdateWindow(hwnd); while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); continue; } ImGui_ImplDX9_NewFrame(); #if 0 // 1. Show a simple window // Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window // automatically called "Debug" { static float f = 0.0f; ImGui::Text("Hello, world!"); ImGui::SliderFloat("float", &f, 0.0f, 1.0f); ImGui::ColorEdit3("clear color", (float *)&clear_col); if (ImGui::Button("Test Window")) show_test_window ^= 1; if (ImGui::Button("Another Window")) show_another_window ^= 1; ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } // 2. Show another simple window, this time using an explicit Begin/End pair if (show_another_window) { ImGui::SetNextWindowSize(ImVec2(200, 100), ImGuiSetCond_FirstUseEver); ImGui::Begin("Another Window", &show_another_window); ImGui::Text("Hello"); ImGui::End(); } #endif #if 0 // 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow() if (show_test_window) { ImGui::SetNextWindowPos(ImVec2(650, 20), ImGuiSetCond_FirstUseEver); ImGui::ShowTestWindow(&show_test_window); } #endif app.Update(); if (app.m_wantsQuit) { PostMessage(hwnd, WM_QUIT, 0, 0); } // Rendering g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false); g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false); D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_col.x * 255.0f), (int)(clear_col.y * 255.0f), (int)(clear_col.z * 255.0f), (int)(clear_col.w * 255.0f)); g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0); if (g_pd3dDevice->BeginScene() >= 0) { ImGui::Render(); g_pd3dDevice->EndScene(); } g_pd3dDevice->Present(NULL, NULL, NULL, NULL); } ImGui_ImplDX9_Shutdown(); if (g_pd3dDevice) g_pd3dDevice->Release(); if (pD3D) pD3D->Release(); UnregisterClass(class_name, wc.hInstance); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QDebug> #include <QScrollBar> #include <QTextBlock> #include <QAbstractTextDocumentLayout> // CTK includes #include "ctkFittedTextBrowser.h" #include "ctkFittedTextBrowser_p.h" static const char moreAnchor[] = "show_details"; static const char lessAnchor[] = "hide_details"; //----------------------------------------------------------------------------- ctkFittedTextBrowserPrivate::ctkFittedTextBrowserPrivate(ctkFittedTextBrowser& object) :q_ptr(&object) { this->Collapsed = true; this->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Text; this->ShowDetailsText = object.tr("Show details..."); this->HideDetailsText = object.tr("Hide details."); QString HideDetailsText; } //----------------------------------------------------------------------------- ctkFittedTextBrowserPrivate::~ctkFittedTextBrowserPrivate() { } //----------------------------------------------------------------------------- void ctkFittedTextBrowserPrivate::updateCollapsedText() { Q_Q(ctkFittedTextBrowser); bool html = (this->CollapsibleTextSetter == ctkFittedTextBrowserPrivate::Html || this->CollapsibleText.indexOf("<html>") >= 0); if (html) { q->setHtml(this->collapsedTextFromHtml()); } else { q->setHtml(this->collapsedTextFromPlainText()); } } //----------------------------------------------------------------------------- QString ctkFittedTextBrowserPrivate::collapsedTextFromPlainText() const { Q_Q(const ctkFittedTextBrowser); int teaserEndPosition = this->CollapsibleText.indexOf("\n"); if (teaserEndPosition < 0) { return this->CollapsibleText; } QString finalText; finalText.append("<html>"); finalText.append(this->Collapsed ? this->CollapsibleText.left(teaserEndPosition) : this->CollapsibleText); finalText.append(this->collapseLinkText()); finalText.append("</html>"); // Remove line break to allow continuation of line. finalText.replace(finalText.indexOf('\n'), 1, ""); // In plain text line breaks were indicated by newline, but we now use html, // so line breaks must use <br> finalText.replace("\n", "<br>"); return finalText; } //----------------------------------------------------------------------------- QString ctkFittedTextBrowserPrivate::collapsedTextFromHtml() const { Q_Q(const ctkFittedTextBrowser); const QString lineBreak("<br>"); int teaserEndPosition = this->CollapsibleText.indexOf(lineBreak); if (teaserEndPosition < 0) { return this->CollapsibleText; } QString finalText = this->CollapsibleText; if (this->Collapsed) { finalText = finalText.left(teaserEndPosition) + this->collapseLinkText(); // By truncating the full text we might have deleted the closing </html> tag // restore it now. if (finalText.contains("<html") && !finalText.contains("</html")) { finalText.append("</html>"); } } else { // Remove <br> to allow continuation of line and avoid extra space // when <p> element is used as well. finalText.replace(finalText.indexOf(lineBreak), lineBreak.size(), ""); // Add link text before closing </body> or </html> tag if (finalText.contains("</body>")) { finalText.replace("</body>", this->collapseLinkText() + "</body>"); } else if (finalText.contains("</html>")) { finalText.replace("</html>", this->collapseLinkText() + "</html>"); } else { finalText.append(this->collapseLinkText()); } } return finalText; } //----------------------------------------------------------------------------- QString ctkFittedTextBrowserPrivate::collapseLinkText() const { Q_Q(const ctkFittedTextBrowser); if (this->Collapsed) { return QString("&hellip; <a href=\"#") + moreAnchor + "\">" + this->ShowDetailsText + "</a>"; } else { return QString(" <a href=\"#") + lessAnchor + "\">" + this->HideDetailsText + "</a>"; } } //----------------------------------------------------------------------------- ctkFittedTextBrowser::ctkFittedTextBrowser(QWidget* _parent) : QTextBrowser(_parent) , d_ptr(new ctkFittedTextBrowserPrivate(*this)) { this->connect(this, SIGNAL(textChanged()), SLOT(heightForWidthMayHaveChanged())); QSizePolicy newSizePolicy = QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); this->setSizePolicy(newSizePolicy); this->connect(this, SIGNAL(anchorClicked(QUrl)), SLOT(anchorClicked(QUrl))); } //----------------------------------------------------------------------------- ctkFittedTextBrowser::~ctkFittedTextBrowser() { } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::heightForWidthMayHaveChanged() { this->updateGeometry(); } //----------------------------------------------------------------------------- int ctkFittedTextBrowser::heightForWidth(int _width) const { QTextDocument* doc = this->document(); qreal savedWidth = doc->textWidth(); // Fudge factor. This is the difference between the frame and the // viewport. int fudge = 2 * this->frameWidth(); int horizontalScrollbarHeight = 0; if (this->horizontalScrollBar()->isVisible()) { horizontalScrollbarHeight = this->horizontalScrollBar()->height() + fudge; } // Do the calculation assuming no scrollbars doc->setTextWidth(_width - fudge); int noScrollbarHeight = doc->documentLayout()->documentSize().height() + fudge; // (If noScrollbarHeight is greater than the maximum height we'll be // allowed, then there will be scrollbars, and the actual required // height will be even higher. But since in this case we've already // hit the maximum height, it doesn't matter that we underestimate.) // Get minimum height (even if string is empty): one line of text int _minimumHeight = QFontMetrics(doc->defaultFont()).lineSpacing() + fudge; int ret = qMax(noScrollbarHeight, _minimumHeight) + horizontalScrollbarHeight; doc->setTextWidth(savedWidth); return ret; } //----------------------------------------------------------------------------- QSize ctkFittedTextBrowser::minimumSizeHint() const { QSize s(this->size().width(), 0); if (s.width() == 0) { //s.setWidth(400); // arbitrary value return QTextBrowser::minimumSizeHint(); } s.setHeight(this->heightForWidth(s.width())); return s; } //----------------------------------------------------------------------------- QSize ctkFittedTextBrowser::sizeHint() const { return this->minimumSizeHint(); } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::resizeEvent(QResizeEvent* e) { this->QTextBrowser::resizeEvent(e); if (e->size().height() != this->heightForWidth(e->size().width())) { this->heightForWidthMayHaveChanged(); } } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setCollapsibleText(const QString &text) { Q_D(ctkFittedTextBrowser); d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Text; d->CollapsibleText = text; d->updateCollapsedText(); } //----------------------------------------------------------------------------- QString ctkFittedTextBrowser::collapsibleText() const { Q_D(const ctkFittedTextBrowser); return d->CollapsibleText; } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setCollapsiblePlainText(const QString &text) { Q_D(ctkFittedTextBrowser); d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::PlainText; d->CollapsibleText = text; d->updateCollapsedText(); } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setCollapsibleHtml(const QString &text) { Q_D(ctkFittedTextBrowser); d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Html; d->CollapsibleText = text; d->updateCollapsedText(); } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::anchorClicked(const QUrl &url) { Q_D(ctkFittedTextBrowser); if (url.path().isEmpty()) { if (url.fragment() == moreAnchor) { this->setCollapsed(false); } else if (url.fragment() == lessAnchor) { this->setCollapsed(true); } } } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setCollapsed(bool collapsed) { Q_D(ctkFittedTextBrowser); if (d->Collapsed == collapsed) { // no change return; } d->Collapsed = collapsed; d->updateCollapsedText(); } //----------------------------------------------------------------------------- bool ctkFittedTextBrowser::collapsed() const { Q_D(const ctkFittedTextBrowser); return d->Collapsed; } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setShowDetailsText(const QString &text) { Q_D(ctkFittedTextBrowser); if (d->ShowDetailsText == text) { // no change return; } d->ShowDetailsText = text; d->updateCollapsedText(); } //----------------------------------------------------------------------------- QString ctkFittedTextBrowser::showDetailsText() const { Q_D(const ctkFittedTextBrowser); return d->ShowDetailsText; } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setHideDetailsText(const QString &text) { Q_D(ctkFittedTextBrowser); if (d->HideDetailsText == text) { // no change return; } d->HideDetailsText = text; d->updateCollapsedText(); } //----------------------------------------------------------------------------- QString ctkFittedTextBrowser::hideDetailsText() const { Q_D(const ctkFittedTextBrowser); return d->HideDetailsText; } <commit_msg>COMP: Fix -Wunused-variable warnings in ctkFittedTextBrowserPrivate<commit_after>/*========================================================================= Library: CTK Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Qt includes #include <QDebug> #include <QScrollBar> #include <QTextBlock> #include <QAbstractTextDocumentLayout> // CTK includes #include "ctkFittedTextBrowser.h" #include "ctkFittedTextBrowser_p.h" static const char moreAnchor[] = "show_details"; static const char lessAnchor[] = "hide_details"; //----------------------------------------------------------------------------- ctkFittedTextBrowserPrivate::ctkFittedTextBrowserPrivate(ctkFittedTextBrowser& object) :q_ptr(&object) { this->Collapsed = true; this->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Text; this->ShowDetailsText = object.tr("Show details..."); this->HideDetailsText = object.tr("Hide details."); QString HideDetailsText; } //----------------------------------------------------------------------------- ctkFittedTextBrowserPrivate::~ctkFittedTextBrowserPrivate() { } //----------------------------------------------------------------------------- void ctkFittedTextBrowserPrivate::updateCollapsedText() { Q_Q(ctkFittedTextBrowser); bool html = (this->CollapsibleTextSetter == ctkFittedTextBrowserPrivate::Html || this->CollapsibleText.indexOf("<html>") >= 0); if (html) { q->setHtml(this->collapsedTextFromHtml()); } else { q->setHtml(this->collapsedTextFromPlainText()); } } //----------------------------------------------------------------------------- QString ctkFittedTextBrowserPrivate::collapsedTextFromPlainText() const { int teaserEndPosition = this->CollapsibleText.indexOf("\n"); if (teaserEndPosition < 0) { return this->CollapsibleText; } QString finalText; finalText.append("<html>"); finalText.append(this->Collapsed ? this->CollapsibleText.left(teaserEndPosition) : this->CollapsibleText); finalText.append(this->collapseLinkText()); finalText.append("</html>"); // Remove line break to allow continuation of line. finalText.replace(finalText.indexOf('\n'), 1, ""); // In plain text line breaks were indicated by newline, but we now use html, // so line breaks must use <br> finalText.replace("\n", "<br>"); return finalText; } //----------------------------------------------------------------------------- QString ctkFittedTextBrowserPrivate::collapsedTextFromHtml() const { const QString lineBreak("<br>"); int teaserEndPosition = this->CollapsibleText.indexOf(lineBreak); if (teaserEndPosition < 0) { return this->CollapsibleText; } QString finalText = this->CollapsibleText; if (this->Collapsed) { finalText = finalText.left(teaserEndPosition) + this->collapseLinkText(); // By truncating the full text we might have deleted the closing </html> tag // restore it now. if (finalText.contains("<html") && !finalText.contains("</html")) { finalText.append("</html>"); } } else { // Remove <br> to allow continuation of line and avoid extra space // when <p> element is used as well. finalText.replace(finalText.indexOf(lineBreak), lineBreak.size(), ""); // Add link text before closing </body> or </html> tag if (finalText.contains("</body>")) { finalText.replace("</body>", this->collapseLinkText() + "</body>"); } else if (finalText.contains("</html>")) { finalText.replace("</html>", this->collapseLinkText() + "</html>"); } else { finalText.append(this->collapseLinkText()); } } return finalText; } //----------------------------------------------------------------------------- QString ctkFittedTextBrowserPrivate::collapseLinkText() const { if (this->Collapsed) { return QString("&hellip; <a href=\"#") + moreAnchor + "\">" + this->ShowDetailsText + "</a>"; } else { return QString(" <a href=\"#") + lessAnchor + "\">" + this->HideDetailsText + "</a>"; } } //----------------------------------------------------------------------------- ctkFittedTextBrowser::ctkFittedTextBrowser(QWidget* _parent) : QTextBrowser(_parent) , d_ptr(new ctkFittedTextBrowserPrivate(*this)) { this->connect(this, SIGNAL(textChanged()), SLOT(heightForWidthMayHaveChanged())); QSizePolicy newSizePolicy = QSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); this->setSizePolicy(newSizePolicy); this->connect(this, SIGNAL(anchorClicked(QUrl)), SLOT(anchorClicked(QUrl))); } //----------------------------------------------------------------------------- ctkFittedTextBrowser::~ctkFittedTextBrowser() { } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::heightForWidthMayHaveChanged() { this->updateGeometry(); } //----------------------------------------------------------------------------- int ctkFittedTextBrowser::heightForWidth(int _width) const { QTextDocument* doc = this->document(); qreal savedWidth = doc->textWidth(); // Fudge factor. This is the difference between the frame and the // viewport. int fudge = 2 * this->frameWidth(); int horizontalScrollbarHeight = 0; if (this->horizontalScrollBar()->isVisible()) { horizontalScrollbarHeight = this->horizontalScrollBar()->height() + fudge; } // Do the calculation assuming no scrollbars doc->setTextWidth(_width - fudge); int noScrollbarHeight = doc->documentLayout()->documentSize().height() + fudge; // (If noScrollbarHeight is greater than the maximum height we'll be // allowed, then there will be scrollbars, and the actual required // height will be even higher. But since in this case we've already // hit the maximum height, it doesn't matter that we underestimate.) // Get minimum height (even if string is empty): one line of text int _minimumHeight = QFontMetrics(doc->defaultFont()).lineSpacing() + fudge; int ret = qMax(noScrollbarHeight, _minimumHeight) + horizontalScrollbarHeight; doc->setTextWidth(savedWidth); return ret; } //----------------------------------------------------------------------------- QSize ctkFittedTextBrowser::minimumSizeHint() const { QSize s(this->size().width(), 0); if (s.width() == 0) { //s.setWidth(400); // arbitrary value return QTextBrowser::minimumSizeHint(); } s.setHeight(this->heightForWidth(s.width())); return s; } //----------------------------------------------------------------------------- QSize ctkFittedTextBrowser::sizeHint() const { return this->minimumSizeHint(); } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::resizeEvent(QResizeEvent* e) { this->QTextBrowser::resizeEvent(e); if (e->size().height() != this->heightForWidth(e->size().width())) { this->heightForWidthMayHaveChanged(); } } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setCollapsibleText(const QString &text) { Q_D(ctkFittedTextBrowser); d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Text; d->CollapsibleText = text; d->updateCollapsedText(); } //----------------------------------------------------------------------------- QString ctkFittedTextBrowser::collapsibleText() const { Q_D(const ctkFittedTextBrowser); return d->CollapsibleText; } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setCollapsiblePlainText(const QString &text) { Q_D(ctkFittedTextBrowser); d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::PlainText; d->CollapsibleText = text; d->updateCollapsedText(); } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setCollapsibleHtml(const QString &text) { Q_D(ctkFittedTextBrowser); d->CollapsibleTextSetter = ctkFittedTextBrowserPrivate::Html; d->CollapsibleText = text; d->updateCollapsedText(); } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::anchorClicked(const QUrl &url) { if (url.path().isEmpty()) { if (url.fragment() == moreAnchor) { this->setCollapsed(false); } else if (url.fragment() == lessAnchor) { this->setCollapsed(true); } } } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setCollapsed(bool collapsed) { Q_D(ctkFittedTextBrowser); if (d->Collapsed == collapsed) { // no change return; } d->Collapsed = collapsed; d->updateCollapsedText(); } //----------------------------------------------------------------------------- bool ctkFittedTextBrowser::collapsed() const { Q_D(const ctkFittedTextBrowser); return d->Collapsed; } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setShowDetailsText(const QString &text) { Q_D(ctkFittedTextBrowser); if (d->ShowDetailsText == text) { // no change return; } d->ShowDetailsText = text; d->updateCollapsedText(); } //----------------------------------------------------------------------------- QString ctkFittedTextBrowser::showDetailsText() const { Q_D(const ctkFittedTextBrowser); return d->ShowDetailsText; } //----------------------------------------------------------------------------- void ctkFittedTextBrowser::setHideDetailsText(const QString &text) { Q_D(ctkFittedTextBrowser); if (d->HideDetailsText == text) { // no change return; } d->HideDetailsText = text; d->updateCollapsedText(); } //----------------------------------------------------------------------------- QString ctkFittedTextBrowser::hideDetailsText() const { Q_D(const ctkFittedTextBrowser); return d->HideDetailsText; } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplicationHtmlDocGenerator.h" #include <stdio.h> #include "otbMacro.h" #include "otbWrapperParameterGroup.h" #include "otbWrapperChoiceParameter.h" namespace otb { namespace Wrapper { #define otbDocHtmlTitleMacro( value ) \ oss << "</style></head><body style=\" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;\"><p align=\"center\" style=\" margin-top:16px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:x-large; font-weight:600;\"><span style=\" font-size:x-large;\">"; \ oss << value; \ oss << "</span></p>"; #define otbDocHtmlTitle1Macro( value ) \ oss << "<p style=\" margin-top:14px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:large; font-weight:600;\"><span style=\" font-size:large;\">"; \ oss << value; \ oss << "</span></p>"; #define otbDocHtmlTitle2Macro( value ) \ oss << "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><span style=\" font-size:medium;\">"; \ oss << value; \ oss << "</span></p>"; #define otbDocHtmlBodyMacro( value ) \ oss << "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">"; \ oss << value; \ oss << "</p>"; #define otbDocHtmlBodyCodeMacro( value ) \ oss << "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Courier New, courier';\">"; \ oss << value; \ oss << "</p>"; #define otbDocHtmlParamMacro( type, param ) \ oss << "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Courier New, courier'; font-weight:600;\"; >"; \ oss << "["<<type<<"] "<< param->GetName() <<": "; \ oss << "</span>"; \ if( std::string(param->GetDescription()).size()!=0 ) \ { \ oss << param->GetDescription(); \ } \ oss << "</p>"; ApplicationHtmlDocGenerator::ApplicationHtmlDocGenerator() { } ApplicationHtmlDocGenerator::~ApplicationHtmlDocGenerator() { } void ApplicationHtmlDocGenerator::GenerateDoc( const Application::Pointer app, std::string & val ) { itk::OStringStream oss; oss << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd\">"; oss << "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">"; oss << "p, li { white-space: pre-wrap; }"; oss << "</style></head><body style=\" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;\">"; otbDocHtmlTitleMacro( app->GetDocName() ); otbDocHtmlTitle1Macro( "Brief Description" ); otbDocHtmlBodyMacro( app->GetDescription() ); otbDocHtmlTitle1Macro( "Tags" ); std::string tagList; if ( app->GetDocTags().size() > 0 ) { for (unsigned int i = 0; i < app->GetDocTags().size() - 1; i++) { tagList.append( app->GetDocTags()[i] ).append(", "); } tagList.append( app->GetDocTags()[app->GetDocTags().size() - 1]); otbDocHtmlBodyMacro( tagList ); } else { otbDocHtmlBodyMacro( "None" ); } otbDocHtmlTitle1Macro("Long Description"); otbDocHtmlBodyMacro( app->GetDocLongDescription() ); otbDocHtmlTitle1Macro("Parameters"); oss << "<ul>"; std::string paramDocs(""); ApplicationHtmlDocGenerator::GetDocParameters( app, paramDocs ); oss<<paramDocs; oss<<"</ul>"; otbDocHtmlTitle1Macro( "Limitations"); otbDocHtmlBodyMacro( app->GetDocLimitations() ); otbDocHtmlTitle1Macro( "Authors" ); otbDocHtmlBodyMacro( app->GetDocAuthors() ); otbDocHtmlTitle1Macro( "See also" ); otbDocHtmlBodyMacro( app->GetDocSeeAlso() ); otbDocHtmlTitle1Macro( "Command line example" ); otbDocHtmlBodyCodeMacro( app->GetDocCLExample() ); oss << "</body></html>"; val = oss.str(); } void ApplicationHtmlDocGenerator::GenerateDoc(const Application::Pointer app, const std::string& filename) { std::string doc; ApplicationHtmlDocGenerator::GenerateDoc( app, doc ); FILE *file = fopen(filename.c_str(), "w"); if (file == NULL) { fprintf(stderr, "Error, can't open file"); itkGenericExceptionMacro( << "Error, can't open file "<<filename<<"."); } fprintf(file, "%s", doc.c_str()); fclose(file); } void ApplicationHtmlDocGenerator::GetDocParameters( const Application::Pointer app, std::string & val) { itk::OStringStream oss; const std::vector<std::string> appKeyList = app->GetParametersKeys( false ); const unsigned int nbOfParam = appKeyList.size(); std::string paramDocs(""); if( nbOfParam == 0) { val = "None"; } else { for( unsigned int i=0; i<nbOfParam; i++ ) { const std::string key(appKeyList[i]); Parameter::Pointer param = app->GetParameterByKey( key ); if( app->GetParameterType(key) == ParameterType_Group) { oss << "<li>"; otbDocHtmlParamMacro( "group", param); std::string grDoc; ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, key ); oss<<grDoc; oss<<"</li><br />"; } else if( app->GetParameterType(key) == ParameterType_Choice ) { oss << "<li>"; otbDocHtmlParamMacro( "choice", param); std::string grDoc; ApplicationHtmlDocGenerator::GetDocParameterChoice(app, grDoc, key); oss<<grDoc; oss<<"</li><br />"; } else { oss << "<li>"; otbDocHtmlParamMacro("param", param); oss << "</li>"; } } } val = oss.str(); } void ApplicationHtmlDocGenerator::GetDocParameterGroup( const Application::Pointer app, std::string & val, const std::string & key ) { Parameter * paramGr = app->GetParameterByKey( key ); if( !dynamic_cast<ParameterGroup *>(paramGr)) { itkGenericExceptionMacro("Invalid parameter type for key "<<key<<", wait for ParameterGroup..."); } ParameterGroup * group = dynamic_cast<ParameterGroup *>(paramGr); const std::vector<std::string> appKeyList = group->GetParametersKeys( false ); unsigned int nbOfParam = appKeyList.size(); itk::OStringStream oss; oss<<"<ul>"; for( unsigned int i=0; i<nbOfParam; i++ ) { const std::string fullKey(std::string(key).append(".").append(appKeyList[i])); Parameter::Pointer param = app->GetParameterByKey( fullKey ); if( app->GetParameterType(fullKey) == ParameterType_Group) { oss<<"<li>"; otbDocHtmlParamMacro( "group", param); std::string grDoc; ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, fullKey ); oss<<grDoc; oss<<"</li>"; } else if( app->GetParameterType(fullKey) == ParameterType_Choice ) { oss<<"<li>"; otbDocHtmlParamMacro( "choice", param); std::string grDoc; ApplicationHtmlDocGenerator::GetDocParameterChoice(app, grDoc, fullKey ); oss<<grDoc; oss<<"</li>"; } else { oss << "<li>"; otbDocHtmlParamMacro( "param", param ); oss <<"</li>"; } } oss<<"</ul>"; val.append(oss.str()); } void ApplicationHtmlDocGenerator::GetDocParameterChoice( const Application::Pointer app, std::string & val, const std::string & key ) { Parameter * paramCh = app->GetParameterByKey( key ); if( !dynamic_cast<ChoiceParameter *>(paramCh)) { itkGenericExceptionMacro("Invalid parameter type for key "<<key<<", wait for ChoiceParameter..."); } ChoiceParameter * choice = dynamic_cast<ChoiceParameter *>(paramCh); const std::vector<std::string> appKeyList = choice->GetChoiceKeys(); unsigned int nbOfParam = choice->GetNbChoices(); itk::OStringStream oss; oss<<"<ul>"; for( unsigned int i=0; i<nbOfParam; i++ ) { const std::string fullKey(std::string(key).append(".").append(appKeyList[i])); ParameterGroup * group = choice->GetChoiceParameterGroupByIndex(i); std::string grDoc; oss << "<li>"; otbDocHtmlParamMacro( "group", group); ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, fullKey ); oss<<grDoc; oss<<"</li>"; } oss<<"</ul>"; val.append(oss.str()); } } } <commit_msg>WRG: fix wrg (format not a string literal and no format arguments)<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplicationHtmlDocGenerator.h" #include <stdio.h> #include "otbMacro.h" #include "otbWrapperParameterGroup.h" #include "otbWrapperChoiceParameter.h" namespace otb { namespace Wrapper { #define otbDocHtmlTitleMacro( value ) \ oss << "</style></head><body style=\" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;\"><p align=\"center\" style=\" margin-top:16px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:x-large; font-weight:600;\"><span style=\" font-size:x-large;\">"; \ oss << value; \ oss << "</span></p>"; #define otbDocHtmlTitle1Macro( value ) \ oss << "<p style=\" margin-top:14px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:large; font-weight:600;\"><span style=\" font-size:large;\">"; \ oss << value; \ oss << "</span></p>"; #define otbDocHtmlTitle2Macro( value ) \ oss << "<p style=\" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:medium; font-weight:600;\"><span style=\" font-size:medium;\">"; \ oss << value; \ oss << "</span></p>"; #define otbDocHtmlBodyMacro( value ) \ oss << "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">"; \ oss << value; \ oss << "</p>"; #define otbDocHtmlBodyCodeMacro( value ) \ oss << "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Courier New, courier';\">"; \ oss << value; \ oss << "</p>"; #define otbDocHtmlParamMacro( type, param ) \ oss << "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-family:'Courier New, courier'; font-weight:600;\"; >"; \ oss << "["<<type<<"] "<< param->GetName() <<": "; \ oss << "</span>"; \ if( std::string(param->GetDescription()).size()!=0 ) \ { \ oss << param->GetDescription(); \ } \ oss << "</p>"; ApplicationHtmlDocGenerator::ApplicationHtmlDocGenerator() { } ApplicationHtmlDocGenerator::~ApplicationHtmlDocGenerator() { } void ApplicationHtmlDocGenerator::GenerateDoc( const Application::Pointer app, std::string & val ) { itk::OStringStream oss; oss << "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd\">"; oss << "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">"; oss << "p, li { white-space: pre-wrap; }"; oss << "</style></head><body style=\" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;\">"; otbDocHtmlTitleMacro( app->GetDocName() ); otbDocHtmlTitle1Macro( "Brief Description" ); otbDocHtmlBodyMacro( app->GetDescription() ); otbDocHtmlTitle1Macro( "Tags" ); std::string tagList; if ( app->GetDocTags().size() > 0 ) { for (unsigned int i = 0; i < app->GetDocTags().size() - 1; i++) { tagList.append( app->GetDocTags()[i] ).append(", "); } tagList.append( app->GetDocTags()[app->GetDocTags().size() - 1]); otbDocHtmlBodyMacro( tagList ); } else { otbDocHtmlBodyMacro( "None" ); } otbDocHtmlTitle1Macro("Long Description"); otbDocHtmlBodyMacro( app->GetDocLongDescription() ); otbDocHtmlTitle1Macro("Parameters"); oss << "<ul>"; std::string paramDocs(""); ApplicationHtmlDocGenerator::GetDocParameters( app, paramDocs ); oss<<paramDocs; oss<<"</ul>"; otbDocHtmlTitle1Macro( "Limitations"); otbDocHtmlBodyMacro( app->GetDocLimitations() ); otbDocHtmlTitle1Macro( "Authors" ); otbDocHtmlBodyMacro( app->GetDocAuthors() ); otbDocHtmlTitle1Macro( "See also" ); otbDocHtmlBodyMacro( app->GetDocSeeAlso() ); otbDocHtmlTitle1Macro( "Command line example" ); otbDocHtmlBodyCodeMacro( app->GetDocCLExample() ); oss << "</body></html>"; val = oss.str(); } void ApplicationHtmlDocGenerator::GenerateDoc(const Application::Pointer app, const std::string& filename) { std::string doc; ApplicationHtmlDocGenerator::GenerateDoc( app, doc ); std::ofstream ofs(filename.c_str()); if (!ofs.is_open()) { fprintf(stderr, "Error, can't open file"); itkGenericExceptionMacro( << "Error, can't open file "<<filename<<"."); } ofs << doc; ofs.close(); } void ApplicationHtmlDocGenerator::GetDocParameters( const Application::Pointer app, std::string & val) { itk::OStringStream oss; const std::vector<std::string> appKeyList = app->GetParametersKeys( false ); const unsigned int nbOfParam = appKeyList.size(); std::string paramDocs(""); if( nbOfParam == 0) { val = "None"; } else { for( unsigned int i=0; i<nbOfParam; i++ ) { const std::string key(appKeyList[i]); Parameter::Pointer param = app->GetParameterByKey( key ); if( app->GetParameterType(key) == ParameterType_Group) { oss << "<li>"; otbDocHtmlParamMacro( "group", param); std::string grDoc; ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, key ); oss<<grDoc; oss<<"</li><br />"; } else if( app->GetParameterType(key) == ParameterType_Choice ) { oss << "<li>"; otbDocHtmlParamMacro( "choice", param); std::string grDoc; ApplicationHtmlDocGenerator::GetDocParameterChoice(app, grDoc, key); oss<<grDoc; oss<<"</li><br />"; } else { oss << "<li>"; otbDocHtmlParamMacro("param", param); oss << "</li>"; } } } val = oss.str(); } void ApplicationHtmlDocGenerator::GetDocParameterGroup( const Application::Pointer app, std::string & val, const std::string & key ) { Parameter * paramGr = app->GetParameterByKey( key ); if( !dynamic_cast<ParameterGroup *>(paramGr)) { itkGenericExceptionMacro("Invalid parameter type for key "<<key<<", wait for ParameterGroup..."); } ParameterGroup * group = dynamic_cast<ParameterGroup *>(paramGr); const std::vector<std::string> appKeyList = group->GetParametersKeys( false ); unsigned int nbOfParam = appKeyList.size(); itk::OStringStream oss; oss<<"<ul>"; for( unsigned int i=0; i<nbOfParam; i++ ) { const std::string fullKey(std::string(key).append(".").append(appKeyList[i])); Parameter::Pointer param = app->GetParameterByKey( fullKey ); if( app->GetParameterType(fullKey) == ParameterType_Group) { oss<<"<li>"; otbDocHtmlParamMacro( "group", param); std::string grDoc; ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, fullKey ); oss<<grDoc; oss<<"</li>"; } else if( app->GetParameterType(fullKey) == ParameterType_Choice ) { oss<<"<li>"; otbDocHtmlParamMacro( "choice", param); std::string grDoc; ApplicationHtmlDocGenerator::GetDocParameterChoice(app, grDoc, fullKey ); oss<<grDoc; oss<<"</li>"; } else { oss << "<li>"; otbDocHtmlParamMacro( "param", param ); oss <<"</li>"; } } oss<<"</ul>"; val.append(oss.str()); } void ApplicationHtmlDocGenerator::GetDocParameterChoice( const Application::Pointer app, std::string & val, const std::string & key ) { Parameter * paramCh = app->GetParameterByKey( key ); if( !dynamic_cast<ChoiceParameter *>(paramCh)) { itkGenericExceptionMacro("Invalid parameter type for key "<<key<<", wait for ChoiceParameter..."); } ChoiceParameter * choice = dynamic_cast<ChoiceParameter *>(paramCh); const std::vector<std::string> appKeyList = choice->GetChoiceKeys(); unsigned int nbOfParam = choice->GetNbChoices(); itk::OStringStream oss; oss<<"<ul>"; for( unsigned int i=0; i<nbOfParam; i++ ) { const std::string fullKey(std::string(key).append(".").append(appKeyList[i])); ParameterGroup * group = choice->GetChoiceParameterGroupByIndex(i); std::string grDoc; oss << "<li>"; otbDocHtmlParamMacro( "group", group); ApplicationHtmlDocGenerator::GetDocParameterGroup( app, grDoc, fullKey ); oss<<grDoc; oss<<"</li>"; } oss<<"</ul>"; val.append(oss.str()); } } } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Configuration_Enumeration_inl_ #define _Stroika_Foundation_Configuration_Enumeration_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <wchar.h> #include "../Debug/Assertions.h" namespace Stroika::Foundation::Configuration { /* ******************************************************************************** ******************************** Configuration::Inc **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM Inc (ENUM e) { return ToEnum<ENUM> (ToInt (e) + 1); } /* ******************************************************************************** ****************************** Configuration::ToInt **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr typename underlying_type<ENUM>::type ToInt (ENUM e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND); return static_cast<typename underlying_type<ENUM>::type> (e); } /* ******************************************************************************** ********************* Configuration::GetDistanceSpanned ************************ ******************************************************************************** */ template <typename ENUM> constexpr make_unsigned_t<typename underlying_type<ENUM>::type> GetDistanceSpanned () { return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ENUM::eCOUNT); } /* ******************************************************************************** ***************************** Configuration::ToEnum **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM ToEnum (typename underlying_type<ENUM>::type e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= static_cast<ENUM> (e) and static_cast<ENUM> (e) <= ENUM::eEND); return static_cast<ENUM> (e); } /* ******************************************************************************** ******************** Configuration::OffsetFromStart **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr make_unsigned_t<typename underlying_type<ENUM>::type> OffsetFromStart (ENUM e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND); return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ToInt (e) - ToInt (ENUM::eSTART)); } template <typename ENUM> inline constexpr ENUM OffsetFromStart (make_unsigned_t<typename underlying_type<ENUM>::type> offset) { return ToEnum<ENUM> (offset + ENUM::eSTART); } /* ******************************************************************************** ************************** Configuration::EnumNames **************************** ******************************************************************************** */ template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::EnumNames (const initializer_list<EnumName<ENUM_TYPE>>& origEnumNames) #if 0 : fEnumNames_{origEnumNames} #endif { #if 1 // @todo find some way to INITIALZIE the static array.... - needed for constexpr function! // @see qCANNOT_FIGURE_OUT_HOW_TO_INIT_STD_ARRAY_FROM_STD_INITIALIZER_ // // Tried fEnumNames_{origEnumNames} and tried template <typename... E> CTOR auto oi = fEnumNames_.begin (); for (EnumName<ENUM_TYPE> i : origEnumNames) { Require (oi != fEnumNames_.end ()); *oi = i; ++oi; } #endif RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> constexpr EnumNames<ENUM_TYPE>::EnumNames (const typename EnumNames<ENUM_TYPE>::BasicArrayInitializer& init) : fEnumNames_{init} { RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> template <size_t N> constexpr EnumNames<ENUM_TYPE>::EnumNames (const EnumName<ENUM_TYPE> origEnumNames[N]) : fEnumNames_{origEnumNames} { RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::operator initializer_list<EnumName<ENUM_TYPE>> () const { return fEnumNames_; } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::begin () const { return fEnumNames_.begin (); } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::end () const { return fEnumNames_.end (); } template <typename ENUM_TYPE> constexpr size_t EnumNames<ENUM_TYPE>::size () const { return fEnumNames_.size (); } template <typename ENUM_TYPE> constexpr const wchar_t* EnumNames<ENUM_TYPE>::PeekName (ENUM_TYPE e) const { if (e == ENUM_TYPE::eEND) { return nullptr; } #if qDebug Require (OffsetFromStart<ENUM_TYPE> (e) < fEnumNames_.size ()); auto refImpl = [this] (ENUM_TYPE e) -> const wchar_t* { for (auto i : fEnumNames_) { if (i.first == e) { return i.second; } } return nullptr; }; Ensure (refImpl (e) == fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second); #endif return fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second; } template <typename ENUM_TYPE> inline const wchar_t* EnumNames<ENUM_TYPE>::GetName (ENUM_TYPE e) const { auto tmp = PeekName (e); RequireNotNull (tmp); return tmp; } template <typename ENUM_TYPE> optional<ENUM_TYPE> EnumNames<ENUM_TYPE>::PeekValue (const wchar_t* name) const { /* * NB: this is only safe returning an internal pointer, because the pointer is internal to * static, immudatable data - the basic_array associated with this EnumNames<> structure. */ RequireNotNull (name); for (const_iterator i = fEnumNames_.begin (); i != fEnumNames_.end (); ++i) { if (::wcscmp (i->second, name) == 0) { return &i->first; } } return nullopt; } template <typename ENUM_TYPE> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name) const { optional<ENUM_TYPE> tmp = PeekValue (name); Require (tmp.has_value ()); return *tmp; } template <typename ENUM_TYPE> template <typename NOT_FOUND_EXCEPTION> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name, const NOT_FOUND_EXCEPTION& notFoundException) const { RequireNotNull (name); optional<ENUM_TYPE> tmp = PeekValue (name); if (!tmp) [[UNLIKELY_ATTR]] { //Execution::Throw (notFoundException); throw (notFoundException); } return *tmp; } template <typename ENUM_TYPE> constexpr void EnumNames<ENUM_TYPE>::RequireItemsOrderedByEnumValue_ () const { Require (static_cast<size_t> (ENUM_TYPE::eCOUNT) == fEnumNames_.size ()); using IndexType = make_unsigned_t<typename underlying_type<ENUM_TYPE>::type>; for (IndexType i = 0; i < static_cast<IndexType> (ENUM_TYPE::eCOUNT); ++i) { Require (OffsetFromStart<ENUM_TYPE> (fEnumNames_[i].first) == i); } } /* ******************************************************************************** ************************** Configuration::DefaultNames ************************* ******************************************************************************** */ template <typename ENUM_TYPE> constexpr DefaultNames<ENUM_TYPE>::DefaultNames () : EnumNames<ENUM_TYPE> (k) { } } #endif /*_Stroika_Foundation_Configuration_Enumeration_inl_*/ <commit_msg>fixed typo<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Configuration_Enumeration_inl_ #define _Stroika_Foundation_Configuration_Enumeration_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <wchar.h> #include "../Debug/Assertions.h" namespace Stroika::Foundation::Configuration { /* ******************************************************************************** ******************************** Configuration::Inc **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM Inc (ENUM e) { return ToEnum<ENUM> (ToInt (e) + 1); } /* ******************************************************************************** ****************************** Configuration::ToInt **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr typename underlying_type<ENUM>::type ToInt (ENUM e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND); return static_cast<typename underlying_type<ENUM>::type> (e); } /* ******************************************************************************** ********************* Configuration::GetDistanceSpanned ************************ ******************************************************************************** */ template <typename ENUM> constexpr make_unsigned_t<typename underlying_type<ENUM>::type> GetDistanceSpanned () { return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ENUM::eCOUNT); } /* ******************************************************************************** ***************************** Configuration::ToEnum **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM ToEnum (typename underlying_type<ENUM>::type e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= static_cast<ENUM> (e) and static_cast<ENUM> (e) <= ENUM::eEND); return static_cast<ENUM> (e); } /* ******************************************************************************** ******************** Configuration::OffsetFromStart **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr make_unsigned_t<typename underlying_type<ENUM>::type> OffsetFromStart (ENUM e) { // https://stroika.atlassian.net/browse/STK-549 //static_assert (ENUM::eSTART <= e and e <= ENUM::eEND); return static_cast<make_unsigned_t<typename underlying_type<ENUM>::type>> (ToInt (e) - ToInt (ENUM::eSTART)); } template <typename ENUM> inline constexpr ENUM OffsetFromStart (make_unsigned_t<typename underlying_type<ENUM>::type> offset) { return ToEnum<ENUM> (offset + ENUM::eSTART); } /* ******************************************************************************** ************************** Configuration::EnumNames **************************** ******************************************************************************** */ template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::EnumNames (const initializer_list<EnumName<ENUM_TYPE>>& origEnumNames) #if 0 : fEnumNames_{origEnumNames} #endif { #if 1 // @todo find some way to INITIALZIE the static array.... - needed for constexpr function! // @see qCANNOT_FIGURE_OUT_HOW_TO_INIT_STD_ARRAY_FROM_STD_INITIALIZER_ // // Tried fEnumNames_{origEnumNames} and tried template <typename... E> CTOR auto oi = fEnumNames_.begin (); for (EnumName<ENUM_TYPE> i : origEnumNames) { Require (oi != fEnumNames_.end ()); *oi = i; ++oi; } #endif RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> constexpr EnumNames<ENUM_TYPE>::EnumNames (const typename EnumNames<ENUM_TYPE>::BasicArrayInitializer& init) : fEnumNames_{init} { RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> template <size_t N> constexpr EnumNames<ENUM_TYPE>::EnumNames (const EnumName<ENUM_TYPE> origEnumNames[N]) : fEnumNames_{origEnumNames} { RequireItemsOrderedByEnumValue_ (); } template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::operator initializer_list<EnumName<ENUM_TYPE>> () const { return fEnumNames_; } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::begin () const { return fEnumNames_.begin (); } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::end () const { return fEnumNames_.end (); } template <typename ENUM_TYPE> constexpr size_t EnumNames<ENUM_TYPE>::size () const { return fEnumNames_.size (); } template <typename ENUM_TYPE> constexpr const wchar_t* EnumNames<ENUM_TYPE>::PeekName (ENUM_TYPE e) const { if (e == ENUM_TYPE::eEND) { return nullptr; } #if qDebug Require (OffsetFromStart<ENUM_TYPE> (e) < fEnumNames_.size ()); auto refImpl = [this] (ENUM_TYPE e) -> const wchar_t* { for (auto i : fEnumNames_) { if (i.first == e) { return i.second; } } return nullptr; }; Ensure (refImpl (e) == fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second); #endif return fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second; } template <typename ENUM_TYPE> inline const wchar_t* EnumNames<ENUM_TYPE>::GetName (ENUM_TYPE e) const { auto tmp = PeekName (e); RequireNotNull (tmp); return tmp; } template <typename ENUM_TYPE> optional<ENUM_TYPE> EnumNames<ENUM_TYPE>::PeekValue (const wchar_t* name) const { /* * NB: this is only safe returning an internal pointer, because the pointer is internal to * static, immudatable data - the basic_array associated with this EnumNames<> structure. */ RequireNotNull (name); for (const_iterator i = fEnumNames_.begin (); i != fEnumNames_.end (); ++i) { if (::wcscmp (i->second, name) == 0) { return i->first; } } return nullopt; } template <typename ENUM_TYPE> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name) const { optional<ENUM_TYPE> tmp = PeekValue (name); Require (tmp.has_value ()); return *tmp; } template <typename ENUM_TYPE> template <typename NOT_FOUND_EXCEPTION> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name, const NOT_FOUND_EXCEPTION& notFoundException) const { RequireNotNull (name); optional<ENUM_TYPE> tmp = PeekValue (name); if (!tmp) [[UNLIKELY_ATTR]] { //Execution::Throw (notFoundException); throw (notFoundException); } return *tmp; } template <typename ENUM_TYPE> constexpr void EnumNames<ENUM_TYPE>::RequireItemsOrderedByEnumValue_ () const { Require (static_cast<size_t> (ENUM_TYPE::eCOUNT) == fEnumNames_.size ()); using IndexType = make_unsigned_t<typename underlying_type<ENUM_TYPE>::type>; for (IndexType i = 0; i < static_cast<IndexType> (ENUM_TYPE::eCOUNT); ++i) { Require (OffsetFromStart<ENUM_TYPE> (fEnumNames_[i].first) == i); } } /* ******************************************************************************** ************************** Configuration::DefaultNames ************************* ******************************************************************************** */ template <typename ENUM_TYPE> constexpr DefaultNames<ENUM_TYPE>::DefaultNames () : EnumNames<ENUM_TYPE>{k} { } } #endif /*_Stroika_Foundation_Configuration_Enumeration_inl_*/ <|endoftext|>
<commit_before><commit_msg>revert gamut::name<commit_after><|endoftext|>
<commit_before>#include "SequenceVectorizer.h" #include "Opts.h" #include "ClusterAnalysis.h" #include "Logger.h" #include "TarjansAlgorithm.h" #include "BarnesHutSNEAdapter.h" #include "KrakenAdapter.h" #include "RnammerAdapter.h" #include "ResultIO.h" #include "IOUtil.h" #include "MLUtil.h" #include "HierarchicalClustering.h" #include <boost/filesystem.hpp> #include <string> #include <fstream> #include <streambuf> #include <future> #include <map> #include <Eigen/Dense> #include "MatrixUtil.h" int main(int argc, char *argv[]) { std::string banner = ""; // build program arguments try { Opts::initializeOnce(argc, argv); std::ifstream ifs(Opts::sharePath() + "/banner.txt"); banner = std::string((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); } catch(const std::exception & e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } // show help if (Opts::needsHelp()) { std::cout << banner << std::endl; std::cout << Opts::helpDesc() << std::endl; return EXIT_SUCCESS; } // configure logger switch (Opts::logLevel()) { case -1: Logger::getInstance().setLevel(Off); break; case 0: Logger::getInstance().setLevel(Error); break; case 1: Logger::getInstance().setLevel(Info); break; case 2: Logger::getInstance().setLevel(Verbose); break; case 3: Logger::getInstance().setLevel(Debug); break; default: throw std::runtime_error("Loglevel undefined!"); } // check for input files if (Opts::inputFASTAs().empty()) { ELOG << "No input FASTA file(s) given (--input-fasta,-i)." << std::endl; return EXIT_FAILURE; } // setup Kraken KrakenAdapter krk; bool krakenExists = krk.krakenExists(); if (!krakenExists) { ELOG << "Kraken not found! It will be disabled.\n- Please make sure that the folders containing the 'kraken' and 'kraken-translate' executables is in your $PATH.\n- Please make sure to supply a database using the --kraken-db switch." << std::endl; } // setup Rnammer bool rmrExists = RnammerAdapter::rnammerExists(); if (!rmrExists) { ELOG << "Rnammer not found! It will be disabled.\n- Please make sure that the folders containing the 'rnammer' executable is in your $PATH." << std::endl; } // create output / export directory boost::filesystem::path exportPath (Opts::outputDir() + "/export"); boost::system::error_code returnedError; boost::filesystem::create_directories(exportPath, returnedError); if (returnedError) { ELOG << "Could not create output/export directory, aborting." << std::endl; return EXIT_FAILURE; } // copy result assets try { IOUtil::copyDir(boost::filesystem::path(Opts::sharePath() + "/assets"), Opts::outputDir(), true); } catch(const boost::filesystem::filesystem_error & e) { ELOG << e.what() << std::endl; return EXIT_FAILURE; } // remove old data.js file if necessary std::string dataFile = Opts::outputDir() + "/data.js"; if (boost::filesystem::exists(boost::filesystem::path(dataFile))) { std::remove(dataFile.c_str()); } // process files ResultIO rio(Opts::outputDir(), krakenExists); unsigned idCnt = 1; for (const auto & fasta : Opts::inputFASTAs()) { if (!boost::filesystem::is_regular_file(boost::filesystem::path(fasta))) { ELOG << "File '" << fasta << "' does not exist or is not a regular file! Skipping..." << std::endl; continue; } ILOG << "Processing file: " << fasta << std::endl; ResultContainer result; result.id = idCnt++; result.fasta = fasta; try { if (krakenExists) { ILOG << "Running Kraken..." << std::endl; try { } catch(const std::exception & e) { result.kraken = krk.runKraken(fasta); ELOG << e.what() << std::endl; ELOG << "Kraken will be disabled." << std::endl; krakenExists = false; } } result.stats = SequenceUtil::calculateStats(fasta, Opts::minContigLength()); ILOG << "Vectorizing contigs..." << std::endl; SequenceVectorizer sv(fasta); auto svr = sv.vectorize(); result.fastaLabels = svr.contigs; if (rmrExists) { ILOG << "Running Rnammer..." << std::endl; try { result._16S = RnammerAdapter::find16S(fasta, svr); } catch(const std::exception & e) { ELOG << e.what() << std::endl; ELOG << "16S highlighting will be disabled." << std::endl; rmrExists = false; } } ILOG << "Clustering..." << std::endl; result.bootstraps = ClusterAnalysis::analyzeBootstraps(svr); result.oneshot = result.bootstraps.at(0); result.bootstraps.erase(result.bootstraps.begin()); rio.processResult(result); } catch(const std::exception & e) { ELOG << "An error occurred processing this file: " << e.what() << std::endl; } } return EXIT_SUCCESS; } <commit_msg>fixed a mistake where kraken didn't run at all<commit_after>#include "SequenceVectorizer.h" #include "Opts.h" #include "ClusterAnalysis.h" #include "Logger.h" #include "TarjansAlgorithm.h" #include "BarnesHutSNEAdapter.h" #include "KrakenAdapter.h" #include "RnammerAdapter.h" #include "ResultIO.h" #include "IOUtil.h" #include "MLUtil.h" #include "HierarchicalClustering.h" #include <boost/filesystem.hpp> #include <string> #include <fstream> #include <streambuf> #include <future> #include <map> #include <Eigen/Dense> #include "MatrixUtil.h" int main(int argc, char *argv[]) { std::string banner = ""; // build program arguments try { Opts::initializeOnce(argc, argv); std::ifstream ifs(Opts::sharePath() + "/banner.txt"); banner = std::string((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>()); } catch(const std::exception & e) { std::cerr << e.what() << std::endl; return EXIT_FAILURE; } // show help if (Opts::needsHelp()) { std::cout << banner << std::endl; std::cout << Opts::helpDesc() << std::endl; return EXIT_SUCCESS; } // configure logger switch (Opts::logLevel()) { case -1: Logger::getInstance().setLevel(Off); break; case 0: Logger::getInstance().setLevel(Error); break; case 1: Logger::getInstance().setLevel(Info); break; case 2: Logger::getInstance().setLevel(Verbose); break; case 3: Logger::getInstance().setLevel(Debug); break; default: throw std::runtime_error("Loglevel undefined!"); } // check for input files if (Opts::inputFASTAs().empty()) { ELOG << "No input FASTA file(s) given (--input-fasta,-i)." << std::endl; return EXIT_FAILURE; } // setup Kraken KrakenAdapter krk; bool krakenExists = krk.krakenExists(); if (!krakenExists) { ELOG << "Kraken not found! It will be disabled.\n- Please make sure that the folders containing the 'kraken' and 'kraken-translate' executables is in your $PATH.\n- Please make sure to supply a database using the --kraken-db switch." << std::endl; } // setup Rnammer bool rmrExists = RnammerAdapter::rnammerExists(); if (!rmrExists) { ELOG << "Rnammer not found! It will be disabled.\n- Please make sure that the folders containing the 'rnammer' executable is in your $PATH." << std::endl; } // create output / export directory boost::filesystem::path exportPath (Opts::outputDir() + "/export"); boost::system::error_code returnedError; boost::filesystem::create_directories(exportPath, returnedError); if (returnedError) { ELOG << "Could not create output/export directory, aborting." << std::endl; return EXIT_FAILURE; } // copy result assets try { IOUtil::copyDir(boost::filesystem::path(Opts::sharePath() + "/assets"), Opts::outputDir(), true); } catch(const boost::filesystem::filesystem_error & e) { ELOG << e.what() << std::endl; return EXIT_FAILURE; } // remove old data.js file if necessary std::string dataFile = Opts::outputDir() + "/data.js"; if (boost::filesystem::exists(boost::filesystem::path(dataFile))) { std::remove(dataFile.c_str()); } // process files ResultIO rio(Opts::outputDir(), krakenExists); unsigned idCnt = 1; for (const auto & fasta : Opts::inputFASTAs()) { if (!boost::filesystem::is_regular_file(boost::filesystem::path(fasta))) { ELOG << "File '" << fasta << "' does not exist or is not a regular file! Skipping..." << std::endl; continue; } ILOG << "Processing file: " << fasta << std::endl; ResultContainer result; result.id = idCnt++; result.fasta = fasta; try { if (krakenExists) { ILOG << "Running Kraken..." << std::endl; try { result.kraken = krk.runKraken(fasta); } catch(const std::exception & e) { ELOG << e.what() << std::endl; ELOG << "Kraken will be disabled." << std::endl; krakenExists = false; } } result.stats = SequenceUtil::calculateStats(fasta, Opts::minContigLength()); ILOG << "Vectorizing contigs..." << std::endl; SequenceVectorizer sv(fasta); auto svr = sv.vectorize(); result.fastaLabels = svr.contigs; if (rmrExists) { ILOG << "Running Rnammer..." << std::endl; try { result._16S = RnammerAdapter::find16S(fasta, svr); } catch(const std::exception & e) { ELOG << e.what() << std::endl; ELOG << "16S highlighting will be disabled." << std::endl; rmrExists = false; } } ILOG << "Clustering..." << std::endl; result.bootstraps = ClusterAnalysis::analyzeBootstraps(svr); result.oneshot = result.bootstraps.at(0); result.bootstraps.erase(result.bootstraps.begin()); rio.processResult(result); } catch(const std::exception & e) { ELOG << "An error occurred processing this file: " << e.what() << std::endl; } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #ifndef _Stroika_Foundation_Configuration_Enumeration_inl_ #define _Stroika_Foundation_Configuration_Enumeration_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" namespace Stroika { namespace Foundation { namespace Configuration { /* ******************************************************************************** ******************************** Configuration::Inc **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM Inc (ENUM e) { return ToEnum<ENUM> (ToInt (e) + 1); } /* ******************************************************************************** ****************************** Configuration::ToInt **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr typename underlying_type<ENUM>::type ToInt (ENUM e) { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (ENUM::eSTART <= e and e <= ENUM::eEND); #endif return static_cast<typename underlying_type<ENUM>::type> (e); } /* ******************************************************************************** ***************************** Configuration::ToEnum **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM ToEnum (typename underlying_type<ENUM>::type e) { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (ENUM::eSTART <= static_cast<ENUM> (e) and static_cast<ENUM> (e) <= ENUM::eEND); #endif return static_cast<ENUM> (e); } /* ******************************************************************************** ******************** Configuration::OffsetFromStart **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr typename make_unsigned<typename underlying_type<ENUM>::type>::type OffsetFromStart (ENUM e) { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (ENUM::eSTART <= e and e <= ENUM::eEND); #endif return static_cast<typename make_unsigned<typename underlying_type<ENUM>::type>::type> (ToInt (e) - ToInt (ENUM::eSTART)); } template <typename ENUM> inline constexpr ENUM OffsetFromStart (typename make_unsigned<typename underlying_type<ENUM>::type>::type offset) { return ToEnum<ENUM> (offset + ENUM::eSTART); } /* ******************************************************************************** ************************** Configuration::EnumNames **************************** ******************************************************************************** */ template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::EnumNames (const initializer_list<EnumName<ENUM_TYPE>>& origEnumNames) : fEnumNames_ () { // @todo find some way to INITIALZIE the static array.... - needed for constexpr function! auto oi = fEnumNames_.begin (); for (EnumName<ENUM_TYPE> i : origEnumNames) { Require (oi != fEnumNames_.end ()); *oi = i; ++oi; } #if qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy) RequireItemsOrderedByEnumValue_ (); #endif } template <typename ENUM_TYPE> inline #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif EnumNames<ENUM_TYPE>::EnumNames (const typename EnumNames<ENUM_TYPE>::BasicArrayInitializer& init) : fEnumNames_ (init) { #if qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy) RequireItemsOrderedByEnumValue_ (); #endif } template <typename ENUM_TYPE> template <size_t N> inline #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif EnumNames<ENUM_TYPE>::EnumNames (const EnumName<ENUM_TYPE> origEnumNames[N]) : fEnumNames_ (origEnumNames) { #if qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy) RequireItemsOrderedByEnumValue_ (); #endif } template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::operator initializer_list<EnumName<ENUM_TYPE>> () const { return fEnumNames_; } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::begin () const { return fEnumNames_.begin (); } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::end () const { return fEnumNames_.end (); } template <typename ENUM_TYPE> inline constexpr size_t EnumNames<ENUM_TYPE>::size () const { return fEnumNames_.size (); } template <typename ENUM_TYPE> inline const wchar_t* EnumNames<ENUM_TYPE>::PeekName (ENUM_TYPE e) const { if (e == ENUM_TYPE::eEND) { return nullptr; } #if qDebug //#if qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy) Require (OffsetFromStart<ENUM_TYPE> (e) < fEnumNames_.size ()); auto refImpl = [this] (ENUM_TYPE e) -> const wchar_t* { for (auto i : fEnumNames_) { if (i.first == e) { return i.second; } } return nullptr; }; Ensure (refImpl (e) == fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second); #endif return fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second; } template <typename ENUM_TYPE> inline const wchar_t* EnumNames<ENUM_TYPE>::GetName (ENUM_TYPE e) const { auto tmp = PeekName (e); RequireNotNull (tmp); return tmp; } template <typename ENUM_TYPE> const ENUM_TYPE* EnumNames<ENUM_TYPE>::PeekValue (const wchar_t* name) const { /* * NB: this is only safe returning an internal pointer, because the pointer is internal to * static, immudatable data - the basic_array associated with this EnumNames<> structure. */ RequireNotNull (name); for (const_iterator i = fEnumNames_.begin (); i != fEnumNames_.end (); ++i) { if (::wcscmp (i->second, name) == 0) { return &i->first; } } return nullptr; } template <typename ENUM_TYPE> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name) const { const ENUM_TYPE* tmp = PeekValue (name); RequireNotNull (tmp); return *tmp; } template <typename ENUM_TYPE> template <typename NOT_FOUND_EXCEPTION> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name, const NOT_FOUND_EXCEPTION& notFoundException) const { RequireNotNull (name); const ENUM_TYPE* tmp = PeekValue (name); if (tmp == nullptr) { //Execution::Throw (notFoundException); throw (notFoundException); } return *tmp; } #if qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy) template <typename ENUM_TYPE> inline constexpr void EnumNames<ENUM_TYPE>::RequireItemsOrderedByEnumValue_ () const { Require (static_cast<size_t> (ENUM_TYPE::eCOUNT) == fEnumNames_.size ()); using IndexType = typename make_unsigned<typename underlying_type<ENUM_TYPE>::type>::type; for (IndexType i = 0; i < static_cast<IndexType> (ENUM_TYPE::eCOUNT); ++i) { Require (OffsetFromStart<ENUM_TYPE> (fEnumNames_[i].first) == i); } } #endif } } } #endif /*_Stroika_Foundation_Configuration_Enumeration_inl_*/ <commit_msg>DefaultNames<ENUM_TYPE>::DefaultNames<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #ifndef _Stroika_Foundation_Configuration_Enumeration_inl_ #define _Stroika_Foundation_Configuration_Enumeration_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "../Debug/Assertions.h" namespace Stroika { namespace Foundation { namespace Configuration { /* ******************************************************************************** ******************************** Configuration::Inc **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM Inc (ENUM e) { return ToEnum<ENUM> (ToInt (e) + 1); } /* ******************************************************************************** ****************************** Configuration::ToInt **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr typename underlying_type<ENUM>::type ToInt (ENUM e) { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (ENUM::eSTART <= e and e <= ENUM::eEND); #endif return static_cast<typename underlying_type<ENUM>::type> (e); } /* ******************************************************************************** ***************************** Configuration::ToEnum **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr ENUM ToEnum (typename underlying_type<ENUM>::type e) { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (ENUM::eSTART <= static_cast<ENUM> (e) and static_cast<ENUM> (e) <= ENUM::eEND); #endif return static_cast<ENUM> (e); } /* ******************************************************************************** ******************** Configuration::OffsetFromStart **************************** ******************************************************************************** */ template <typename ENUM> inline constexpr typename make_unsigned<typename underlying_type<ENUM>::type>::type OffsetFromStart (ENUM e) { #if !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy Require (ENUM::eSTART <= e and e <= ENUM::eEND); #endif return static_cast<typename make_unsigned<typename underlying_type<ENUM>::type>::type> (ToInt (e) - ToInt (ENUM::eSTART)); } template <typename ENUM> inline constexpr ENUM OffsetFromStart (typename make_unsigned<typename underlying_type<ENUM>::type>::type offset) { return ToEnum<ENUM> (offset + ENUM::eSTART); } /* ******************************************************************************** ************************** Configuration::EnumNames **************************** ******************************************************************************** */ template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::EnumNames (const initializer_list<EnumName<ENUM_TYPE>>& origEnumNames) : fEnumNames_ () { // @todo find some way to INITIALZIE the static array.... - needed for constexpr function! auto oi = fEnumNames_.begin (); for (EnumName<ENUM_TYPE> i : origEnumNames) { Require (oi != fEnumNames_.end ()); *oi = i; ++oi; } #if qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy) RequireItemsOrderedByEnumValue_ (); #endif } template <typename ENUM_TYPE> inline #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif EnumNames<ENUM_TYPE>::EnumNames (const typename EnumNames<ENUM_TYPE>::BasicArrayInitializer& init) : fEnumNames_ (init) { #if qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy) RequireItemsOrderedByEnumValue_ (); #endif } template <typename ENUM_TYPE> template <size_t N> inline #if !qCompilerAndStdLib_constexpr_Buggy constexpr #endif EnumNames<ENUM_TYPE>::EnumNames (const EnumName<ENUM_TYPE> origEnumNames[N]) : fEnumNames_ (origEnumNames) { #if qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy) RequireItemsOrderedByEnumValue_ (); #endif } template <typename ENUM_TYPE> inline EnumNames<ENUM_TYPE>::operator initializer_list<EnumName<ENUM_TYPE>> () const { return fEnumNames_; } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::begin () const { return fEnumNames_.begin (); } template <typename ENUM_TYPE> inline typename EnumNames<ENUM_TYPE>::const_iterator EnumNames<ENUM_TYPE>::end () const { return fEnumNames_.end (); } template <typename ENUM_TYPE> inline constexpr size_t EnumNames<ENUM_TYPE>::size () const { return fEnumNames_.size (); } template <typename ENUM_TYPE> inline const wchar_t* EnumNames<ENUM_TYPE>::PeekName (ENUM_TYPE e) const { if (e == ENUM_TYPE::eEND) { return nullptr; } #if qDebug //#if qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy) Require (OffsetFromStart<ENUM_TYPE> (e) < fEnumNames_.size ()); auto refImpl = [this] (ENUM_TYPE e) -> const wchar_t* { for (auto i : fEnumNames_) { if (i.first == e) { return i.second; } } return nullptr; }; Ensure (refImpl (e) == fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second); #endif return fEnumNames_[OffsetFromStart<ENUM_TYPE> (e)].second; } template <typename ENUM_TYPE> inline const wchar_t* EnumNames<ENUM_TYPE>::GetName (ENUM_TYPE e) const { auto tmp = PeekName (e); RequireNotNull (tmp); return tmp; } template <typename ENUM_TYPE> const ENUM_TYPE* EnumNames<ENUM_TYPE>::PeekValue (const wchar_t* name) const { /* * NB: this is only safe returning an internal pointer, because the pointer is internal to * static, immudatable data - the basic_array associated with this EnumNames<> structure. */ RequireNotNull (name); for (const_iterator i = fEnumNames_.begin (); i != fEnumNames_.end (); ++i) { if (::wcscmp (i->second, name) == 0) { return &i->first; } } return nullptr; } template <typename ENUM_TYPE> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name) const { const ENUM_TYPE* tmp = PeekValue (name); RequireNotNull (tmp); return *tmp; } template <typename ENUM_TYPE> template <typename NOT_FOUND_EXCEPTION> inline ENUM_TYPE EnumNames<ENUM_TYPE>::GetValue (const wchar_t* name, const NOT_FOUND_EXCEPTION& notFoundException) const { RequireNotNull (name); const ENUM_TYPE* tmp = PeekValue (name); if (tmp == nullptr) { //Execution::Throw (notFoundException); throw (notFoundException); } return *tmp; } #if qDebug && (qCompilerAndStdLib_constexpr_Buggy || !qCompilerAndStdLib_constexpr_functions_cpp14Constaints_Buggy) template <typename ENUM_TYPE> inline constexpr void EnumNames<ENUM_TYPE>::RequireItemsOrderedByEnumValue_ () const { Require (static_cast<size_t> (ENUM_TYPE::eCOUNT) == fEnumNames_.size ()); using IndexType = typename make_unsigned<typename underlying_type<ENUM_TYPE>::type>::type; for (IndexType i = 0; i < static_cast<IndexType> (ENUM_TYPE::eCOUNT); ++i) { Require (OffsetFromStart<ENUM_TYPE> (fEnumNames_[i].first) == i); } } #endif /* ******************************************************************************** ************************** Configuration::DefaultNames ************************* ******************************************************************************** */ template <typename ENUM_TYPE> inline DefaultNames<ENUM_TYPE>::DefaultNames () : EnumNames<ENUM_TYPE> (k) { } } } } #endif /*_Stroika_Foundation_Configuration_Enumeration_inl_*/ <|endoftext|>
<commit_before><commit_msg>Fix argument of write with rvalue reference<commit_after><|endoftext|>
<commit_before>// // Created by ariel on 10/30/16. // #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "Tower/Tower.h" #include "Tower/TowerMan.h" #include "Location/TileUtil.h" #include "State/StateManager.h" using std::cout; using std::endl; using Towers::Tower; using Towers::TowerType; using Towers::TowerMan; using Monsters::MonsterMan; using Location::TileUtil; int main () { // Breaks on 4:3, large screen sizes, but is an acceptable scaling solution for now double scale = sf::VideoMode::getDesktopMode().height / 1080; sf::RenderWindow window(sf::VideoMode(1000, 1000, 32), "Tower Defense", sf::Style::Close); TileUtil::init(1000, 1000); TileUtil::loadMap("Resources/Maps/TestMap.json"); StateManager *stateManager = new StateManager; UIManager uiManager(window, *stateManager); MonsterMan monstMan(window, uiManager, *stateManager); TowerMan towerMan(window, monstMan); window.setFramerateLimit(240); sf::SoundBuffer fireSound; fireSound.loadFromFile("Resources/Sounds/TowerFireSound-1.wav"); sf::Sound sound; sound.setBuffer(fireSound); //sound1.play(); while (window.isOpen()) { sf::Event event; while(window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } else if (event.type == sf::Event::MouseButtonReleased) { if (stateManager->removeCoins(100)) { towerMan.createTower(TowerType::SHORT_RANGE, sf::Mouse::getPosition(window).x, sf::Mouse::getPosition(window).y); } else { cout << "Insufficient funds" << endl; // This should be an onscreen/audio error } } } window.clear(sf::Color::Black); TileUtil::render(window); towerMan.update(); towerMan.render(); monstMan.update(); monstMan.render(); uiManager.update(); uiManager.render(); window.display(); } return 0; } <commit_msg>Updated main<commit_after>// // Created by ariel on 10/30/16. // #include <iostream> #include <SFML/Graphics.hpp> #include <SFML/Audio.hpp> #include "Tower/Tower.h" #include "Tower/TowerMan.h" #include "Location/TileUtil.h" using std::cout; using std::endl; using Towers::Tower; using Towers::TowerType; using Towers::TowerMan; using Monsters::MonsterMan; using Location::TileUtil; int main () { // Breaks on 4:3, large screen sizes, but is an acceptable scaling solution for now double scale = sf::VideoMode::getDesktopMode().height / 1080; sf::RenderWindow window(sf::VideoMode(1000, 1000, 32), "Tower Defense", sf::Style::Close); TileUtil::init(1000, 1000); TileUtil::loadMap("Resources/Maps/TestMap.json"); StateManager *stateManager = new StateManager; UIManager uiManager(window, *stateManager); MonsterMan monstMan(window, uiManager, *stateManager); TowerMan towerMan(window, monstMan); monstMan.createMonster(); window.setFramerateLimit(240); sf::SoundBuffer fireSound; fireSound.loadFromFile("Resources/Sounds/TowerFireSound-1.wav"); sf::Sound sound; sound.setBuffer(fireSound); //sound1.play(); while (window.isOpen()) { sf::Event event; while(window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } else if (event.type == sf::Event::MouseButtonReleased) { if (stateManager->removeCoins(100)) { towerMan.createTower(TowerType::SHORT_RANGE, sf::Mouse::getPosition(window).x, sf::Mouse::getPosition(window).y); } else { cout << "Insufficient funds" << endl; // This should be an onscreen/audio error } } } TileUtil::render(window); towerMan.update(); towerMan.render(); monstMan.update(); monstMan.render(); uiManager.update(); uiManager.render(); window.display(); } return 0; } <|endoftext|>
<commit_before><commit_msg>automated merge<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // #define VERBOSE_DEBUG #define LOG_TAG "Minikin" #include <cutils/log.h> #include "MinikinInternal.h" #include <minikin/CmapCoverage.h> #include <minikin/FontCollection.h> using std::vector; namespace android { template <typename T> static inline T max(T a, T b) { return a>b ? a : b; } uint32_t FontCollection::sNextId = 0; FontCollection::FontCollection(const vector<FontFamily*>& typefaces) : mMaxChar(0) { AutoMutex _l(gMinikinLock); mId = sNextId++; vector<uint32_t> lastChar; size_t nTypefaces = typefaces.size(); #ifdef VERBOSE_DEBUG ALOGD("nTypefaces = %d\n", nTypefaces); #endif const FontStyle defaultStyle; for (size_t i = 0; i < nTypefaces; i++) { FontFamily* family = typefaces[i]; family->RefLocked(); FontInstance dummy; mInstances.push_back(dummy); // emplace_back would be better FontInstance* instance = &mInstances.back(); instance->mFamily = family; instance->mCoverage = new SparseBitSet; MinikinFont* typeface = family->getClosestMatch(defaultStyle).font; if (typeface == NULL) { ALOGE("FontCollection: closest match was null"); // TODO: we shouldn't hit this, as there should be more robust // checks upstream to prevent empty/invalid FontFamily objects continue; } #ifdef VERBOSE_DEBUG ALOGD("closest match = %p, family size = %d\n", typeface, family->getNumFonts()); #endif const uint32_t cmapTag = MinikinFont::MakeTag('c', 'm', 'a', 'p'); size_t cmapSize = 0; bool ok = typeface->GetTable(cmapTag, NULL, &cmapSize); UniquePtr<uint8_t[]> cmapData(new uint8_t[cmapSize]); ok = typeface->GetTable(cmapTag, cmapData.get(), &cmapSize); CmapCoverage::getCoverage(*instance->mCoverage, cmapData.get(), cmapSize); #ifdef VERBOSE_DEBUG ALOGD("font coverage length=%d, first ch=%x\n", instance->mCoverage->length(), instance->mCoverage->nextSetBit(0)); #endif mMaxChar = max(mMaxChar, instance->mCoverage->length()); lastChar.push_back(instance->mCoverage->nextSetBit(0)); } size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage; size_t offset = 0; for (size_t i = 0; i < nPages; i++) { Range dummy; mRanges.push_back(dummy); Range* range = &mRanges.back(); #ifdef VERBOSE_DEBUG ALOGD("i=%d: range start = %d\n", i, offset); #endif range->start = offset; for (size_t j = 0; j < nTypefaces; j++) { if (lastChar[j] < (i + 1) << kLogCharsPerPage) { const FontInstance* instance = &mInstances[j]; mInstanceVec.push_back(instance); offset++; uint32_t nextChar = instance->mCoverage->nextSetBit((i + 1) << kLogCharsPerPage); #ifdef VERBOSE_DEBUG ALOGD("nextChar = %d (j = %d)\n", nextChar, j); #endif lastChar[j] = nextChar; } } range->end = offset; } } FontCollection::~FontCollection() { for (size_t i = 0; i < mInstances.size(); i++) { delete mInstances[i].mCoverage; mInstances[i].mFamily->UnrefLocked(); } } // Implement heuristic for choosing best-match font. Here are the rules: // 1. If first font in the collection has the character, it wins. // 2. If a font matches both language and script, it gets a score of 4. // 3. If a font matches just language, it gets a score of 2. // 4. Matching the "compact" or "elegant" variant adds one to the score. // 5. Highest score wins, with ties resolved to the first font. const FontCollection::FontInstance* FontCollection::getInstanceForChar(uint32_t ch, FontLanguage lang, int variant) const { if (ch >= mMaxChar) { return NULL; } const Range& range = mRanges[ch >> kLogCharsPerPage]; #ifdef VERBOSE_DEBUG ALOGD("querying range %d:%d\n", range.start, range.end); #endif const FontInstance* bestInstance = NULL; int bestScore = -1; for (size_t i = range.start; i < range.end; i++) { const FontInstance* instance = mInstanceVec[i]; if (instance->mCoverage->get(ch)) { FontFamily* family = instance->mFamily; // First font family in collection always matches if (mInstances[0].mFamily == family) { return instance; } int score = lang.match(family->lang()) * 2; if (variant != 0 && variant == family->variant()) { score++; } if (score > bestScore) { bestScore = score; bestInstance = instance; } } } return bestInstance; } void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style, vector<Run>* result) const { FontLanguage lang = style.getLanguage(); int variant = style.getVariant(); const FontInstance* lastInstance = NULL; Run* run = NULL; int nShorts; for (size_t i = 0; i < string_size; i += nShorts) { nShorts = 1; uint32_t ch = string[i]; // sigh, decode UTF-16 by hand here if ((ch & 0xfc00) == 0xd800) { if ((i + 1) < string_size) { ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff); nShorts = 2; } } // Continue using existing font as long as it has coverage. if (lastInstance == NULL || !lastInstance->mCoverage->get(ch)) { const FontInstance* instance = getInstanceForChar(ch, lang, variant); if (i == 0 || instance != lastInstance) { Run dummy; result->push_back(dummy); run = &result->back(); if (instance == NULL) { run->fakedFont.font = NULL; } else { run->fakedFont = instance->mFamily->getClosestMatch(style); } lastInstance = instance; run->start = i; } } run->end = i + nShorts; } } MinikinFont* FontCollection::baseFont(FontStyle style) { return baseFontFaked(style).font; } FakedFont FontCollection::baseFontFaked(FontStyle style) { if (mInstances.empty()) { return FakedFont(); } return mInstances[0].mFamily->getClosestMatch(style); } uint32_t FontCollection::getId() const { return mId; } } // namespace android <commit_msg>Fix missing text on nonexistent font file<commit_after>/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // #define VERBOSE_DEBUG #define LOG_TAG "Minikin" #include <cutils/log.h> #include "MinikinInternal.h" #include <minikin/CmapCoverage.h> #include <minikin/FontCollection.h> using std::vector; namespace android { template <typename T> static inline T max(T a, T b) { return a>b ? a : b; } uint32_t FontCollection::sNextId = 0; FontCollection::FontCollection(const vector<FontFamily*>& typefaces) : mMaxChar(0) { AutoMutex _l(gMinikinLock); mId = sNextId++; vector<uint32_t> lastChar; size_t nTypefaces = typefaces.size(); #ifdef VERBOSE_DEBUG ALOGD("nTypefaces = %d\n", nTypefaces); #endif const FontStyle defaultStyle; for (size_t i = 0; i < nTypefaces; i++) { FontFamily* family = typefaces[i]; MinikinFont* typeface = family->getClosestMatch(defaultStyle).font; if (typeface == NULL) { ALOGE("FontCollection: closest match was null"); // TODO: we shouldn't hit this, as there should be more robust // checks upstream to prevent empty/invalid FontFamily objects continue; } family->RefLocked(); FontInstance dummy; mInstances.push_back(dummy); // emplace_back would be better FontInstance* instance = &mInstances.back(); instance->mFamily = family; instance->mCoverage = new SparseBitSet; #ifdef VERBOSE_DEBUG ALOGD("closest match = %p, family size = %d\n", typeface, family->getNumFonts()); #endif const uint32_t cmapTag = MinikinFont::MakeTag('c', 'm', 'a', 'p'); size_t cmapSize = 0; bool ok = typeface->GetTable(cmapTag, NULL, &cmapSize); UniquePtr<uint8_t[]> cmapData(new uint8_t[cmapSize]); ok = typeface->GetTable(cmapTag, cmapData.get(), &cmapSize); CmapCoverage::getCoverage(*instance->mCoverage, cmapData.get(), cmapSize); #ifdef VERBOSE_DEBUG ALOGD("font coverage length=%d, first ch=%x\n", instance->mCoverage->length(), instance->mCoverage->nextSetBit(0)); #endif mMaxChar = max(mMaxChar, instance->mCoverage->length()); lastChar.push_back(instance->mCoverage->nextSetBit(0)); } nTypefaces = mInstances.size(); size_t nPages = (mMaxChar + kPageMask) >> kLogCharsPerPage; size_t offset = 0; for (size_t i = 0; i < nPages; i++) { Range dummy; mRanges.push_back(dummy); Range* range = &mRanges.back(); #ifdef VERBOSE_DEBUG ALOGD("i=%d: range start = %d\n", i, offset); #endif range->start = offset; for (size_t j = 0; j < nTypefaces; j++) { if (lastChar[j] < (i + 1) << kLogCharsPerPage) { const FontInstance* instance = &mInstances[j]; mInstanceVec.push_back(instance); offset++; uint32_t nextChar = instance->mCoverage->nextSetBit((i + 1) << kLogCharsPerPage); #ifdef VERBOSE_DEBUG ALOGD("nextChar = %d (j = %d)\n", nextChar, j); #endif lastChar[j] = nextChar; } } range->end = offset; } } FontCollection::~FontCollection() { for (size_t i = 0; i < mInstances.size(); i++) { delete mInstances[i].mCoverage; mInstances[i].mFamily->UnrefLocked(); } } // Implement heuristic for choosing best-match font. Here are the rules: // 1. If first font in the collection has the character, it wins. // 2. If a font matches both language and script, it gets a score of 4. // 3. If a font matches just language, it gets a score of 2. // 4. Matching the "compact" or "elegant" variant adds one to the score. // 5. Highest score wins, with ties resolved to the first font. const FontCollection::FontInstance* FontCollection::getInstanceForChar(uint32_t ch, FontLanguage lang, int variant) const { if (ch >= mMaxChar) { return NULL; } const Range& range = mRanges[ch >> kLogCharsPerPage]; #ifdef VERBOSE_DEBUG ALOGD("querying range %d:%d\n", range.start, range.end); #endif const FontInstance* bestInstance = NULL; int bestScore = -1; for (size_t i = range.start; i < range.end; i++) { const FontInstance* instance = mInstanceVec[i]; if (instance->mCoverage->get(ch)) { FontFamily* family = instance->mFamily; // First font family in collection always matches if (mInstances[0].mFamily == family) { return instance; } int score = lang.match(family->lang()) * 2; if (variant != 0 && variant == family->variant()) { score++; } if (score > bestScore) { bestScore = score; bestInstance = instance; } } } return bestInstance; } void FontCollection::itemize(const uint16_t *string, size_t string_size, FontStyle style, vector<Run>* result) const { FontLanguage lang = style.getLanguage(); int variant = style.getVariant(); const FontInstance* lastInstance = NULL; Run* run = NULL; int nShorts; for (size_t i = 0; i < string_size; i += nShorts) { nShorts = 1; uint32_t ch = string[i]; // sigh, decode UTF-16 by hand here if ((ch & 0xfc00) == 0xd800) { if ((i + 1) < string_size) { ch = 0x10000 + ((ch & 0x3ff) << 10) + (string[i + 1] & 0x3ff); nShorts = 2; } } // Continue using existing font as long as it has coverage. if (lastInstance == NULL || !lastInstance->mCoverage->get(ch)) { const FontInstance* instance = getInstanceForChar(ch, lang, variant); if (i == 0 || instance != lastInstance) { Run dummy; result->push_back(dummy); run = &result->back(); if (instance == NULL) { run->fakedFont.font = NULL; } else { run->fakedFont = instance->mFamily->getClosestMatch(style); } lastInstance = instance; run->start = i; } } run->end = i + nShorts; } } MinikinFont* FontCollection::baseFont(FontStyle style) { return baseFontFaked(style).font; } FakedFont FontCollection::baseFontFaked(FontStyle style) { if (mInstances.empty()) { return FakedFont(); } return mInstances[0].mFamily->getClosestMatch(style); } uint32_t FontCollection::getId() const { return mId; } } // namespace android <|endoftext|>
<commit_before>#include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/compression/octree_pointcloud_compression.h> #include <stdio.h> #include <sstream> #include <stdlib.h> #ifdef WIN32 # define sleep(x) Sleep((x)*1000) #endif class SimpleOpenNIViewer { public: SimpleOpenNIViewer () : viewer (" Point Cloud Compression Example") { } void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud) { if (!viewer.wasStopped ()) { // stringstream to store compressed point cloud std::stringstream compressedData; // output pointcloud pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloudOut (new pcl::PointCloud<pcl::PointXYZRGBA> ()); // compress point cloud PointCloudEncoder->encodePointCloud (cloud, compressedData); // decompress point cloud PointCloudDecoder->decodePointCloud (compressedData, cloudOut); // show decompressed point cloud viewer.showCloud (cloudOut); } } void run () { bool showStatistics = true; // for a full list of profiles see: /io/include/pcl/compression/compression_profiles.h pcl::octree::compression_Profiles_e compressionProfile = pcl::octree::MED_RES_ONLINE_COMPRESSION_WITH_COLOR; // instantiate point cloud compression for encoding and decoding PointCloudEncoder = new pcl::octree::PointCloudCompression<pcl::PointXYZRGBA> (compressionProfile, showStatistics); PointCloudDecoder = new pcl::octree::PointCloudCompression<pcl::PointXYZRGBA> (); // create a new grabber for OpenNI devices pcl::Grabber* interface = new pcl::OpenNIGrabber (); // make callback function from member function boost::function<void (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)> f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1); // connect callback function for desired signal. In this case its a point cloud with color values boost::signals2::connection c = interface->registerCallback (f); // start receiving point clouds interface->start (); while (!viewer.wasStopped ()) { sleep (1); } interface->stop (); // delete point cloud compression instances delete (PointCloudEncoder); delete (PointCloudDecoder); } pcl::visualization::CloudViewer viewer; pcl::octree::PointCloudCompression<pcl::PointXYZRGBA>* PointCloudEncoder; pcl::octree::PointCloudCompression<pcl::PointXYZRGBA>* PointCloudDecoder; }; int main (int argc, char **argv) { SimpleOpenNIViewer v; v.run (); return (0); } <commit_msg>adjusting point_cloud_compression.cpp to recent code changes<commit_after>#include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/io/openni_grabber.h> #include <pcl/visualization/cloud_viewer.h> #include <pcl/compression/octree_pointcloud_compression.h> #include <stdio.h> #include <sstream> #include <stdlib.h> #ifdef WIN32 # define sleep(x) Sleep((x)*1000) #endif class SimpleOpenNIViewer { public: SimpleOpenNIViewer () : viewer (" Point Cloud Compression Example") { } void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr &cloud) { if (!viewer.wasStopped ()) { // stringstream to store compressed point cloud std::stringstream compressedData; // output pointcloud pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloudOut (new pcl::PointCloud<pcl::PointXYZRGBA> ()); // compress point cloud PointCloudEncoder->encodePointCloud (cloud, compressedData); // decompress point cloud PointCloudDecoder->decodePointCloud (compressedData, cloudOut); // show decompressed point cloud viewer.showCloud (cloudOut); } } void run () { bool showStatistics = true; // for a full list of profiles see: /io/include/pcl/compression/compression_profiles.h pcl::octree::compression_Profiles_e compressionProfile = pcl::octree::MED_RES_ONLINE_COMPRESSION_WITH_COLOR; // instantiate point cloud compression for encoding and decoding PointCloudEncoder = new pcl::io::OctreePointCloudCompression<pcl::PointXYZRGBA> (compressionProfile, showStatistics); PointCloudDecoder = new pcl::io::OctreePointCloudCompression<pcl::PointXYZRGBA> (); // create a new grabber for OpenNI devices pcl::Grabber* interface = new pcl::OpenNIGrabber (); // make callback function from member function boost::function<void (const pcl::PointCloud<pcl::PointXYZRGBA>::ConstPtr&)> f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1); // connect callback function for desired signal. In this case its a point cloud with color values boost::signals2::connection c = interface->registerCallback (f); // start receiving point clouds interface->start (); while (!viewer.wasStopped ()) { sleep (1); } interface->stop (); // delete point cloud compression instances delete (PointCloudEncoder); delete (PointCloudDecoder); } pcl::visualization::CloudViewer viewer; pcl::io::OctreePointCloudCompression<pcl::PointXYZRGBA>* PointCloudEncoder; pcl::io::OctreePointCloudCompression<pcl::PointXYZRGBA>* PointCloudDecoder; }; int main (int argc, char **argv) { SimpleOpenNIViewer v; v.run (); return (0); } <|endoftext|>
<commit_before>/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2002 by the OpenSG Forum * * * * www.opensg.org * * * * contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <OpenSG/OSGConfig.h> #include <OpenSG/OSGBaseInitFunctions.h> #define SVN_REVISION "382" /*! Append our version to the library versions string */ static bool versionAdder(void) { OSG::addLibraryVersion("OSGBase: " OSG_VERSION_STRING "\tRev: " SVN_REVISION ); return true; } static OSG::StaticInitFuncWrapper versionAdderWrapper(versionAdder); <commit_msg>fixed : include problems<commit_after>/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2002 by the OpenSG Forum * * * * www.opensg.org * * * * contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- // Includes //--------------------------------------------------------------------------- #include <OSGConfig.h> #include <OSGBaseInitFunctions.h> #define SVN_REVISION "382" /*! Append our version to the library versions string */ static bool versionAdder(void) { OSG::addLibraryVersion("OSGBase: " OSG_VERSION_STRING "\tRev: " SVN_REVISION ); return true; } static OSG::StaticInitFuncWrapper versionAdderWrapper(versionAdder); <|endoftext|>
<commit_before>#ifndef NGS_ARCHIVE_BASE #define NGS_ARCHIVE_BASE namespace ngstd { class Archive { public: virtual bool Output () = 0; virtual bool Input () { return !Output(); } virtual Archive & operator & (double & d) = 0; virtual Archive & operator & (int & i) = 0; virtual Archive & operator & (long & i) = 0; virtual Archive & operator & (size_t & i) = 0; virtual Archive & operator & (short & i) = 0; virtual Archive & operator & (unsigned char & i) = 0; virtual Archive & operator & (bool & b) = 0; virtual Archive & operator & (string & str) = 0; virtual Archive & operator & (char *& str) = 0; template <typename T> Archive & operator << (const T & t) { T ht(t); (*this) & ht; return *this; } }; } #endif <commit_msg>archive array-functions<commit_after>#ifndef NGS_ARCHIVE_BASE #define NGS_ARCHIVE_BASE // copied from netgen namespace ngstd { class Archive { public: virtual bool Output () = 0; virtual bool Input () { return !Output(); } virtual Archive & operator & (double & d) = 0; virtual Archive & operator & (int & i) = 0; virtual Archive & operator & (long & i) = 0; virtual Archive & operator & (size_t & i) = 0; virtual Archive & operator & (short & i) = 0; virtual Archive & operator & (unsigned char & i) = 0; virtual Archive & operator & (bool & b) = 0; virtual Archive & operator & (string & str) = 0; virtual Archive & operator & (char *& str) = 0; template <typename T> Archive & Do (T * data, size_t n) { for (size_t j = 0; j < n; j++) { (*this) & data[j]; }; return *this; }; virtual Archive & Do (double * d, size_t n) { for (size_t j = 0; j < n; j++) { (*this) & d[j]; }; return *this; }; virtual Archive & Do (int * i, size_t n) { for (size_t j = 0; j < n; j++) { (*this) & i[j]; }; return *this; }; virtual Archive & Do (long * i, size_t n) { for (size_t j = 0; j < n; j++) { (*this) & i[j]; }; return *this; }; virtual Archive & Do (size_t * i, size_t n) { for (size_t j = 0; j < n; j++) { (*this) & i[j]; }; return *this; }; virtual Archive & Do (short * i, size_t n) { for (size_t j = 0; j < n; j++) { (*this) & i[j]; }; return *this; }; virtual Archive & Do (unsigned char * i, size_t n) { for (size_t j = 0; j < n; j++) { (*this) & i[j]; }; return *this; }; virtual Archive & Do (bool * b, size_t n) { for (size_t j = 0; j < n; j++) { (*this) & b[j]; }; return *this; }; // nvirtual Archive & Do (string * str, size_t n) // { for (size_t j = 0; j < n; j++) { (*this) & str[j]; }; return *this; }; // virtual Archive & operator & (char *& str) = 0; template <typename T> Archive & operator << (const T & t) { T ht(t); (*this) & ht; return *this; } }; } #endif <|endoftext|>
<commit_before>#include <QCoreApplication> #include "Network.IRC.Server.hpp" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Network::IRC::Server srv("irc.rizon.net", 9999, &a); srv.connect("testos", "Test-App", true); return a.exec(); } <commit_msg>Rewrite of main()<commit_after>#include <QtCore/QCoreApplication> #include "Network.IRC.Server.hpp" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); Network::IRC::Server *srv = new Network::IRC::Server("irc.rizon.net", 9999); // Join channel when connected to server // Now with 100% more lambda voodoo QObject::connect(srv, &Network::IRC::Server::connected, [&](){ srv->join("mr-bigbang"); }); QObject::connect(srv, &Network::IRC::Server::quitting, &a, &QCoreApplication::quit); srv->connect("testos", "Test-App", true); return a.exec(); } <|endoftext|>
<commit_before>// Copyright 2015 Lluís Ulzurrun de Asanza Sàez #include <nds.h> #include <nds/debug.h> #include <sstream> #include "./debug.h" //------------------------------------------------------------------------------ // Graphic references //------------------------------------------------------------------------------ #include "./gfx_ball.h" #include "./gfx_brick.h" #include "./gfx_gradient.h" //------------------------------------------------------------------------------ // Tile entries //------------------------------------------------------------------------------ #define TILE_EMPTY 0 // Tile 0 = empty #define TILE_BRICK 1 // Tile 1 = brick #define TILE_GRADIENT 2 // Tile 2 = gradient // Macro for calculating BG VRAM memory address with tile index. #define tile2bgram(t) (BG_GFX + (t) * 16) //------------------------------------------------------------------------------ // Palette entries //------------------------------------------------------------------------------ #define PAL_BRICKS 0 // Brick palette (entry 0->15). #define PAL_GRADIENT 1 // Gradient palette (entry 16->31). #define BACKDROP_COLOR RGB8(190, 255, 255) // Macro for calculating BG VRAM memory address with palette index. #define pal2bgram(p) (BG_PALETTE + (p) * 16) //------------------------------------------------------------------------------ // BG Screen Base Blocks pointed //------------------------------------------------------------------------------ #define bg0map (reinterpret_cast<u16*>BG_MAP_RAM(1)) #define bg1map (reinterpret_cast<u16*>BG_MAP_RAM(2)) //------------------------------------------------------------------------------ // Main code section //------------------------------------------------------------------------------ /** * Sets up graphics. */ void setupGraphics(void) { vramSetBankE(VRAM_E_MAIN_BG); vramSetBankF(VRAM_F_MAIN_SPRITE); // Generate the first blank tile by clearing it to zero. for ( int n = 0; n < 16; n++ ) BG_GFX[n] = 0; // Copy BG graphics. dmaCopyHalfWords(3, gfx_brickTiles, tile2bgram(TILE_BRICK), gfx_brickTilesLen); dmaCopyHalfWords(3, gfx_gradientTiles, tile2bgram(TILE_GRADIENT), gfx_gradientTilesLen); // Palettes go to palette memory. dmaCopyHalfWords(3, gfx_brickPal, pal2bgram(PAL_BRICKS), gfx_brickPalLen); dmaCopyHalfWords(3, gfx_gradientPal, pal2bgram(PAL_GRADIENT), gfx_gradientPalLen); // Set backdrop color. BG_PALETTE[0] = BACKDROP_COLOR; // libnds prefixes the register names with REG_ REG_BG0CNT = BG_MAP_BASE(1); REG_BG1CNT = BG_MAP_BASE(2); } void update_logic() { } void update_graphics() { // Clear entire bricks' tilemap and gradient's tilemap to zero for ( int n = 0; n < 1024; n++ ) { bg0map[n] = 0; bg1map[n] = 0; } // Set tilemap entries for 6 first rows of background 0 (bricks). for ( int y = 0; y < 6; y++ ) { int y32 = y * 32; for ( int x = 0; x < 32; x++ ) { // Magical formula to calculate if the tile needs to be flipped. // Basically: x & 1 -> AND operation between both numbers, that is: // if last bit is 1, 1, if not, 0. This allows to check // if a number is odd or even in a very fast way. // y & 1 -> Works in the very same way as x & 1. // ^ is the xor operator. int hflip = (x & 1) ^ (y & 1); // Set the tilemap entry. // (PAL_BRICKS << 12) remains there because it is computed at // compile time! bg0map[x + y32] = TILE_BRICK | (hflip << 10) | (PAL_BRICKS << 12); } } // Did we say 6 first rows? We wanted 6 LAST rows! REG_BG0VOFS = 112; // Set tilemap entries for 8 first rows of background 1 (gradient). for ( int y = 0; y < 8; y++ ) { int tile = TILE_GRADIENT + y; int y32 = y * 32; for ( int x = 0; x < 32; x++ ) bg1map[x + y32] = tile | (PAL_GRADIENT << 12); } videoSetMode(MODE_0_2D | DISPLAY_BG0_ACTIVE | DISPLAY_BG1_ACTIVE); } int main(void) { irqInit(); // Initialize interrups. irqEnable(IRQ_VBLANK); // Enable vblank interrupt. setupGraphics(); while (1) { // Rendering period: // Update game objects. update_logic(); // Wait for the vblank period. swiWaitForVBlank(); // VBlank period: (safe yo modify graphics) // Move the graphics around. update_graphics(); } } <commit_msg>Added alpha blending<commit_after>// Copyright 2015 Lluís Ulzurrun de Asanza Sàez #include <nds.h> #include <nds/debug.h> #include <sstream> #include "./debug.h" //------------------------------------------------------------------------------ // Graphic references //------------------------------------------------------------------------------ #include "./gfx_ball.h" #include "./gfx_brick.h" #include "./gfx_gradient.h" //------------------------------------------------------------------------------ // Tile entries //------------------------------------------------------------------------------ #define TILE_EMPTY 0 // Tile 0 = empty #define TILE_BRICK 1 // Tile 1 = brick #define TILE_GRADIENT 2 // Tile 2 = gradient // Macro for calculating BG VRAM memory address with tile index. #define tile2bgram(t) (BG_GFX + (t) * 16) //------------------------------------------------------------------------------ // Palette entries //------------------------------------------------------------------------------ #define PAL_BRICKS 0 // Brick palette (entry 0->15). #define PAL_GRADIENT 1 // Gradient palette (entry 16->31). #define BACKDROP_COLOR RGB8(190, 255, 255) // Macro for calculating BG VRAM memory address with palette index. #define pal2bgram(p) (BG_PALETTE + (p) * 16) //------------------------------------------------------------------------------ // BG Screen Base Blocks pointed //------------------------------------------------------------------------------ #define bg0map (reinterpret_cast<u16*>BG_MAP_RAM(1)) #define bg1map (reinterpret_cast<u16*>BG_MAP_RAM(2)) //------------------------------------------------------------------------------ // Main code section //------------------------------------------------------------------------------ /** * Sets up graphics. */ void setupGraphics(void) { vramSetBankE(VRAM_E_MAIN_BG); vramSetBankF(VRAM_F_MAIN_SPRITE); // Generate the first blank tile by clearing it to zero. for ( int n = 0; n < 16; n++ ) BG_GFX[n] = 0; // Copy BG graphics. dmaCopyHalfWords(3, gfx_brickTiles, tile2bgram(TILE_BRICK), gfx_brickTilesLen); dmaCopyHalfWords(3, gfx_gradientTiles, tile2bgram(TILE_GRADIENT), gfx_gradientTilesLen); // Palettes go to palette memory. dmaCopyHalfWords(3, gfx_brickPal, pal2bgram(PAL_BRICKS), gfx_brickPalLen); dmaCopyHalfWords(3, gfx_gradientPal, pal2bgram(PAL_GRADIENT), gfx_gradientPalLen); // Set backdrop color. BG_PALETTE[0] = BACKDROP_COLOR; // libnds prefixes the register names with REG_ REG_BG0CNT = BG_MAP_BASE(1); REG_BG1CNT = BG_MAP_BASE(2); } void update_logic() { } void update_graphics() { // Clear entire bricks' tilemap and gradient's tilemap to zero for ( int n = 0; n < 1024; n++ ) { bg0map[n] = 0; bg1map[n] = 0; } // Set tilemap entries for 6 first rows of background 0 (bricks). for ( int y = 0; y < 6; y++ ) { int y32 = y * 32; for ( int x = 0; x < 32; x++ ) { // Magical formula to calculate if the tile needs to be flipped. // Basically: x & 1 -> AND operation between both numbers, that is: // if last bit is 1, 1, if not, 0. This allows to check // if a number is odd or even in a very fast way. // y & 1 -> Works in the very same way as x & 1. // ^ is the xor operator. int hflip = (x & 1) ^ (y & 1); // Set the tilemap entry. // (PAL_BRICKS << 12) remains there because it is computed at // compile time! bg0map[x + y32] = TILE_BRICK | (hflip << 10) | (PAL_BRICKS << 12); } } // Did we say 6 first rows? We wanted 6 LAST rows! REG_BG0VOFS = 112; // Set tilemap entries for 8 first rows of background 1 (gradient). for ( int y = 0; y < 8; y++ ) { int tile = TILE_GRADIENT + y; int y32 = y * 32; for ( int x = 0; x < 32; x++ ) bg1map[x + y32] = tile | (PAL_GRADIENT << 12); } // Enable alpha blending of background 1. // My guess: BLEND_DST_BACKDROP is the 14th bit at 1, BLEND_SRC_BG1 is the // 2nd bit at 1 and BLEND_ALPHA are bits 8th and 7th at 10. // BLEND_DST_BACKDROP 0010000000000000 // BLEND_SRC_BG1 0000000000000010 // BLEND_ALPHA 0000000010000000 // ----------------------------------- // 0010000010000010 REG_BLDCNT = BLEND_ALPHA | BLEND_SRC_BG1 | BLEND_DST_BACKDROP; REG_BLDALPHA = (4) + (16 << 8); // This is computed at compile time. videoSetMode(MODE_0_2D | DISPLAY_BG0_ACTIVE | DISPLAY_BG1_ACTIVE); } int main(void) { irqInit(); // Initialize interrups. irqEnable(IRQ_VBLANK); // Enable vblank interrupt. setupGraphics(); while (1) { // Rendering period: // Update game objects. update_logic(); // Wait for the vblank period. swiWaitForVBlank(); // VBlank period: (safe yo modify graphics) // Move the graphics around. update_graphics(); } } <|endoftext|>
<commit_before>#include <limits> //#include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <iostream> #include <fstream> #include <vector> /* #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> */ #ifdef _WIN32 #ifndef EFU_SIMPLEREADHKLMKEY_H #include "simple_read_hklm_key.h" #endif #ifndef EFU_TARGET_H #include "target.h" #endif #ifndef EFU_WINERRORSTRING_H #include "win_error_string.h" #endif #endif #ifndef EFU_EFULAUNCHER_H #include "efulauncher.h" #endif #ifndef EFU_CURLEASY_H #include "curleasy.h" #endif bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = static_cast<char>(tolower(c)); } while (c != 'y' && c != 'n'); return c == 'y'; } int main(int argc, char *argv[]) { CurlGlobalInit curl_global; #ifdef _WIN32 std::string nwn_bin("nwmain.exe"); std::string nwn_root_dir("./"); std::ifstream nwn(nwn_root_dir + nwn_bin, std::ios::binary); if (!nwn) { std::cout << "Current launcher directory not detected as NWN root"\ " directory."; nwn_root_dir = "C:/NeverwinterNights/NWN/"; std::cout << "\nTrying " << nwn_root_dir << "... "; nwn.open(nwn_root_dir + nwn_bin, std::ios::binary); if (!nwn) { std::cout << "not found.\nSearching registry... "; SimpleReadHKLMKey reg("SOFTWARE\\BioWare\\NWN\\Neverwinter", "Location"); if (reg.good()) { nwn_root_dir = reg.str(); std::cout << "key found."; auto path_sep = nwn_root_dir.at(nwn_root_dir.size() - 1); if (path_sep != '/' && path_sep != '\\') { nwn_root_dir.append("/"); } std::cout << "\nTrying " << nwn_root_dir << "... "; nwn.open(nwn_root_dir + nwn_bin, std::ios::binary); if (!nwn) { std::cout << "not found."; } } else { std::cout << "no key found."; } } } if (nwn) { std::cout << nwn_bin << " found." << std::endl; } else { std::cout << "\n\nNWN root directory not found, known"\ " options exhausted."\ "\nThe launcher will not be able to download files to the correct"\ " location or"\ "\nlaunch Neverwinter Nights, however, the launcher"\ " may still download files to"\ "\nthe current directory and you can"\ " move them manually afterwards. To avoid this"\ "\nin the future"\ " either move the launcher to the NWN root directory containing"\ "\nnwmain.exe or pass the -nwn=C:/NeverwinterNights/NWN flag to"\ " the launcher"\ "\nexecutable, substituting the correct path, quoted"\ " if it contains spaces:"\ "\n\t-nwn=\"X:/Games/Neverwinter Nights/NWN\"."\ "\n/ and \\ are interchangeable."\ "\nWould you like to download files anyway (y/n)?" << std::endl; if (!confirm()) { std::cout << "Exiting EfU Launcher. Goodbye!" << std::endl; return 0; } nwn_root_dir = "./"; } #endif EfuLauncher l(nwn_root_dir, "https://raw.github.com/commonquail/efulauncher/"\ "master/versioncheck"); if (l.has_update()) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use"\ " the latest launcher. Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; if (l.get_update()) { std::cout << "Done. Please extract and run the new launcher." << std::endl; } return 0; } } try { l.stat_targets(); std::cout << "Done." << std::endl; } catch (std::exception &e) { std::cerr << e.what() << std::endl; } #ifdef _WIN32 if (nwn) { std::cout << "Launching " << nwn_root_dir + nwn_bin << "..." << std::endl; STARTUPINFO si; PROCESS_INFORMATION pi; ::ZeroMemory(&pi, sizeof(pi)); ::ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); auto nwn_path(nwn_root_dir + nwn_bin); auto cmd_line(nwn_path + " +connect nwn.efupw.com:5121"); const std::vector<const std::string> args(argv + 1, argv + argc); for (size_t i = 0; i < args.size(); ++i) { auto arg(args.at(i)); if (arg.find("-dmpass") == 0) { auto cmd(split(arg, '=')); if (cmd.size() == 2) { cmd_line.append(" -dmc +password " + cmd.at(1)); } else { std::cout << "-dmpass specified but no value given. Use\n"\ "-dmpass=mypassword" <<std::endl; } } else if (arg.find("-nwn") == 0) { auto cmd(split(arg, '=')); if (cmd.size() == 2) { // cmd_line.append(" -nwn " + cmd.at(1)); } else { std::cout << "-nwn specified but no value given. Use\n"\ "-nwn=\"path\\to\\NWN\\directory\\" <<std::endl; } } else { std::cout << "Ignoring unrecognized argument: " << arg << std::endl; } } BOOL success = ::CreateProcess( const_cast<char *>(nwn_path.c_str()), const_cast<char *>(cmd_line.c_str()), NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block const_cast<char *>(nwn_root_dir.c_str()), // Starting directory &si, &pi); if (success) { ::CloseHandle(pi.hProcess); ::CloseHandle(pi.hThread); } else { WinErrorString we; std::cout << we.str() << std::endl; } } #endif return 0; } <commit_msg>Reorganize main().<commit_after>#include <limits> //#include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <iostream> #include <fstream> #include <vector> /* #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> */ #ifdef _WIN32 #ifndef EFU_SIMPLEREADHKLMKEY_H #include "simple_read_hklm_key.h" #endif #ifndef EFU_TARGET_H #include "target.h" #endif #ifndef EFU_WINERRORSTRING_H #include "win_error_string.h" #endif #endif #ifndef EFU_EFULAUNCHER_H #include "efulauncher.h" #endif #ifndef EFU_CURLEASY_H #include "curleasy.h" #endif bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = static_cast<char>(tolower(c)); } while (c != 'y' && c != 'n'); return c == 'y'; } int main(int argc, char *argv[]) { CurlGlobalInit curl_global; bool arg_errors = false; #ifdef _WIN32 std::string nwn_bin("nwmain.exe"); std::string nwn_root_dir("./"); #endif std::string cmd_line(" +connect nwn.efupw.com:5121"); const std::vector<const std::string> args(argv + 1, argv + argc); std::cout << "Processing command line arguments." << std::endl; for (size_t i = 0; i < args.size(); ++i) { auto arg(args.at(i)); if (arg.find("-dmpass") == 0) { auto cmd(split(arg, '=')); if (cmd.size() == 2) { cmd_line.append(" -dmc +password " + cmd.at(1)); } else { std::cout << "-dmpass specified but no value given. Use\n"\ "-dmpass=mypassword" <<std::endl; arg_errors = true; } } else if (arg.find("-nwn") == 0) { auto cmd(split(arg, '=')); if (cmd.size() == 2) { nwn_root_dir = cmd.at(1); } else { std::cout << "-nwn specified but no value given. Use\n"\ "-nwn=\"path\\to\\NWN\\directory\\\"" <<std::endl; arg_errors = true; } } else { std::cout << "Ignoring unrecognized argument: " << arg << std::endl; arg_errors = true; } } if (arg_errors) { std::cout << "Argument errors. Press a key to continue." << std::endl; std::cin.get(); } #ifdef _WIN32 std::ifstream nwn(nwn_root_dir + nwn_bin, std::ios::binary); if (!nwn && nwn_root_dir != "./") { std::cout << nwn_root_dir << " not detected as NWN root directory."\ "\nTrying current launcher directory...\n"; nwn_root_dir = "./"; nwn.open(nwn_root_dir + nwn_bin, std::ios::binary); } if (!nwn) { std::cout << "Current launcher directory not detected as NWN root"\ " directory."; nwn_root_dir = "C:/NeverwinterNights/NWN/"; std::cout << "\nTrying " << nwn_root_dir << "... "; nwn.open(nwn_root_dir + nwn_bin, std::ios::binary); if (!nwn) { std::cout << "not found.\nSearching registry... "; SimpleReadHKLMKey reg("SOFTWARE\\BioWare\\NWN\\Neverwinter", "Location"); if (reg.good()) { nwn_root_dir = reg.str(); std::cout << "key found."; auto path_sep = nwn_root_dir.at(nwn_root_dir.size() - 1); if (path_sep != '/' && path_sep != '\\') { nwn_root_dir.append("/"); } std::cout << "\nTrying " << nwn_root_dir << "... "; nwn.open(nwn_root_dir + nwn_bin, std::ios::binary); if (!nwn) { std::cout << "not found."; } } else { std::cout << "no key found."; } } } if (nwn) { std::cout << nwn_root_dir + nwn_bin << " found." << std::endl; } else { std::cout << "\n\nNWN root directory not found, known"\ " options exhausted."\ "\nThe launcher will not be able to download files to the correct"\ " location or"\ "\nlaunch Neverwinter Nights, however, the launcher"\ " may still download files to"\ "\nthe current directory and you can"\ " move them manually afterwards. To avoid this"\ "\nin the future"\ " either move the launcher to the NWN root directory containing"\ "\nnwmain.exe or pass the -nwn=C:/NeverwinterNights/NWN flag to"\ " the launcher"\ "\nexecutable, substituting the correct path, quoted"\ " if it contains spaces:"\ "\n\t-nwn=\"X:/Games/Neverwinter Nights/NWN\"."\ "\n/ and \\ are interchangeable."\ "\nWould you like to download files anyway (y/n)?" << std::endl; if (!confirm()) { std::cout << "Exiting EfU Launcher. Goodbye!" << std::endl; return 0; } nwn_root_dir = "./"; } #endif EfuLauncher l(nwn_root_dir, "https://raw.github.com/commonquail/efulauncher/"\ "master/versioncheck"); if (l.has_update()) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use"\ " the latest launcher. Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; if (l.get_update()) { std::cout << "Done. Please extract and run the new launcher." << std::endl; } return 0; } } try { l.stat_targets(); std::cout << "Done." << std::endl; } catch (std::exception &e) { std::cerr << e.what() << std::endl; } #ifdef _WIN32 if (nwn) { std::cout << "Launching " << nwn_root_dir + nwn_bin << "..." << std::endl; STARTUPINFO si; PROCESS_INFORMATION pi; ::ZeroMemory(&pi, sizeof(pi)); ::ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); auto nwn_path(nwn_root_dir + nwn_bin); cmd_line = nwn_path + cmd_line; BOOL success = ::CreateProcess( const_cast<char *>(nwn_path.c_str()), const_cast<char *>(cmd_line.c_str()), NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block const_cast<char *>(nwn_root_dir.c_str()), // Starting directory &si, &pi); if (success) { ::CloseHandle(pi.hProcess); ::CloseHandle(pi.hThread); } else { WinErrorString we; std::cout << we.str() << std::endl; } } #endif return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <cstring> #include <vector> using namespace std; void display_name() { /*char* login = getlogin(); if(!getlogin()) //displays the username perror("getlogin"); */ char log[BUFSIZ]; getlogin_r(log, BUFSIZ); char host_name[BUFSIZ]; if(gethostname(host_name, BUFSIZ)== -1) //displays the host name perror("gethostname"); char directory_name[BUFSIZ]; if(getcwd(directory_name, BUFSIZ) == NULL) //displays the directory perror("getcwd"); cout << log << "@" << host_name << ":" << directory_name << "$ "; } bool contain_exit(char** terminate) { string exit_p = *terminate; if(exit_p == "exit") return true; else return false; } void tokenizer(string& conditional, char**& lol, char*& the_token) { string user_input; string space = " "; string or_c = "||"; string and_c = "&&"; string semi_c = ";"; int count = 0; size_t neg_f = -1; char** new_lol = (char**)malloc(BUFSIZ); bool token_flag = false; while(!token_flag && the_token != NULL) { string b = the_token; if((b.find(or_c) != neg_f) || (b.find(and_c) != neg_f) || (b.find(semi_c) != neg_f)) { token_flag = true; } if(!token_flag) { new_lol[count] = the_token; } else { new_lol[count] = NULL; conditional = b; } count++; the_token = strtok(NULL, " "); } if(!token_flag) { new_lol[count] = NULL; } lol = new_lol; //return lol; } bool run_execvp(char** arg) { if(*arg == NULL) return false; int pid = fork(); if(pid == -1) //if couldn't fork, returns perror { perror("fork"); exit(1); } else if(pid == 0) { if(-1 != execvp(arg[0], arg)) return true; else { perror("execvp"); exit(1); } } else if(pid > 0) { if(wait(0) == -1) perror("There was an error waiting"); //somehow an error during waiting //char** argv = arg; string init = arg[0]; if(contain_exit(arg)); else if(init == "true") return true; else if(init == "false") return false; return true; } return false; } int main(int argc, char* argv[]) { while(cin.good()) //whenever there is a system call remember to have perror { display_name(); string user_input; string space = " "; string or_c = "||"; string and_c = "&&"; string semi_c = ";"; string num_s = "#"; getline(cin, user_input); int num_i = user_input.find(num_s, 0); if(num_i >= 0) { user_input = user_input.substr(0,num_i); } int index = 0; string::iterator it; for(it = user_input.begin(); it < user_input.end(); it++, index++) { int wtf = user_input.find(semi_c, index); int lamp = user_input.find(or_c, index); int melon = user_input.find(and_c, index); if(wtf >= 0 && (wtf < lamp || lamp == -1) && (wtf < melon || melon == -1)) { user_input.insert(user_input.find(semi_c, index), " "); user_input.insert(user_input.find(semi_c, index)+1, " "); it = user_input.begin(); it += user_input.find(semi_c, index) +1; index = user_input.find(semi_c, index) +1; } else if(lamp >= 0 && (lamp < wtf || wtf == -1) && (lamp < melon || melon == -1)) { user_input.insert(user_input.find(or_c, index), " "); user_input.insert(user_input.find(or_c, index)+2, " "); it = user_input.begin(); it += user_input.find(or_c, index) + 2; index = user_input.find(or_c, index) +2; } else if(melon >= 0 && (melon < wtf || wtf == -1) && (melon < lamp || lamp == -1)) { user_input.insert(user_input.find(and_c, index), " "); user_input.insert(user_input.find(and_c, index)+2, " "); it = user_input.begin(); it += user_input.find(and_c, index) + 2; index = user_input.find(and_c, index) +2; } } char* womp = (char*)user_input.c_str(); char* token; token = strtok(womp, " "); while(token != NULL) { char** lol; string condition; bool prev_or = false; bool prev_and = true; while(token != NULL) { tokenizer(condition, lol, token); if(*lol != NULL && !prev_or && prev_and) if(contain_exit(lol)) exit(1); if(condition == or_c) { if(prev_or) { /*tokenizer(condition,lol,token); if(*lol != NULL) if(contain_exit(lol)) exit(1);*/ } else if(!prev_and) { prev_and = true; prev_or = false; } else if(run_execvp(lol) == true) { if(token != NULL) { //tokenizer(condition,lol,token); prev_or = true; } else {} } } else if(condition == and_c) { if(!prev_and) { /*tokenizer(condition,lol,token); if(*lol != NULL) if(contain_exit(lol)) exit(1);*/ } else if(prev_or) { //if(run_execvp(lol)); /* if(*lol != NULL) if(contain_exit(lol)) exit(1);*/ prev_or = false; } else if(run_execvp(lol) == false) { if(token != NULL) { //tokenizer(condition,lol,token); prev_and = false; } else {} } } else if(condition == semi_c && !prev_or) { if(run_execvp(lol)); prev_or = false; prev_and = true; } else { if(run_execvp(lol)); } } break; } } return 0; } <commit_msg>removed current directory output<commit_after>#include <iostream> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> #include <cstring> #include <vector> using namespace std; void display_name() { /*char* login = getlogin(); if(!getlogin()) //displays the username perror("getlogin"); */ char log[BUFSIZ]; getlogin_r(log, BUFSIZ); char host_name[BUFSIZ]; if(gethostname(host_name, BUFSIZ)== -1) //displays the host name perror("gethostname"); /*char directory_name[BUFSIZ]; if(getcwd(directory_name, BUFSIZ) == NULL) //displays the directory perror("getcwd");*/ cout << log << "@" << host_name << ":" /*<< directory_name*/ << "$ "; } bool contain_exit(char** terminate) { string exit_p = *terminate; if(exit_p == "exit") return true; else return false; } void tokenizer(string& conditional, char**& lol, char*& the_token) { string user_input; string space = " "; string or_c = "||"; string and_c = "&&"; string semi_c = ";"; int count = 0; size_t neg_f = -1; char** new_lol = (char**)malloc(BUFSIZ); bool token_flag = false; while(!token_flag && the_token != NULL) { string b = the_token; if((b.find(or_c) != neg_f) || (b.find(and_c) != neg_f) || (b.find(semi_c) != neg_f)) { token_flag = true; } if(!token_flag) { new_lol[count] = the_token; } else { new_lol[count] = NULL; conditional = b; } count++; the_token = strtok(NULL, " "); } if(!token_flag) { new_lol[count] = NULL; } lol = new_lol; //return lol; } bool run_execvp(char** arg) { if(*arg == NULL) return false; int pid = fork(); if(pid == -1) //if couldn't fork, returns perror { perror("fork"); exit(1); } else if(pid == 0) { if(-1 != execvp(arg[0], arg)) return true; else { perror("execvp"); exit(1); } } else if(pid > 0) { if(wait(0) == -1) perror("There was an error waiting"); //somehow an error during waiting //char** argv = arg; string init = arg[0]; if(contain_exit(arg)); else if(init == "true") return true; else if(init == "false") return false; return true; } return false; } int main(int argc, char* argv[]) { while(cin.good()) //whenever there is a system call remember to have perror { display_name(); string user_input; string space = " "; string or_c = "||"; string and_c = "&&"; string semi_c = ";"; string num_s = "#"; getline(cin, user_input); int num_i = user_input.find(num_s, 0); if(num_i >= 0) { user_input = user_input.substr(0,num_i); } int index = 0; string::iterator it; for(it = user_input.begin(); it < user_input.end(); it++, index++) { int wtf = user_input.find(semi_c, index); int lamp = user_input.find(or_c, index); int melon = user_input.find(and_c, index); if(wtf >= 0 && (wtf < lamp || lamp == -1) && (wtf < melon || melon == -1)) { user_input.insert(user_input.find(semi_c, index), " "); user_input.insert(user_input.find(semi_c, index)+1, " "); it = user_input.begin(); it += user_input.find(semi_c, index) +1; index = user_input.find(semi_c, index) +1; } else if(lamp >= 0 && (lamp < wtf || wtf == -1) && (lamp < melon || melon == -1)) { user_input.insert(user_input.find(or_c, index), " "); user_input.insert(user_input.find(or_c, index)+2, " "); it = user_input.begin(); it += user_input.find(or_c, index) + 2; index = user_input.find(or_c, index) +2; } else if(melon >= 0 && (melon < wtf || wtf == -1) && (melon < lamp || lamp == -1)) { user_input.insert(user_input.find(and_c, index), " "); user_input.insert(user_input.find(and_c, index)+2, " "); it = user_input.begin(); it += user_input.find(and_c, index) + 2; index = user_input.find(and_c, index) +2; } } char* womp = (char*)user_input.c_str(); char* token; token = strtok(womp, " \t\n"); while(token != NULL) { char** lol; string condition; bool prev_or = false; bool prev_and = true; while(token != NULL) { tokenizer(condition, lol, token); if(*lol != NULL && !prev_or && prev_and) if(contain_exit(lol)) exit(1); if(condition == or_c) { if(prev_or) { /*tokenizer(condition,lol,token); if(*lol != NULL) if(contain_exit(lol)) exit(1);*/ } else if(!prev_and) { prev_and = true; prev_or = false; } else if(run_execvp(lol) == true) { if(token != NULL) { //tokenizer(condition,lol,token); prev_or = true; } else {} } } else if(condition == and_c) { if(!prev_and) { /*tokenizer(condition,lol,token); if(*lol != NULL) if(contain_exit(lol)) exit(1);*/ } else if(prev_or) { //if(run_execvp(lol)); /* if(*lol != NULL) if(contain_exit(lol)) exit(1);*/ prev_or = false; } else if(run_execvp(lol) == false) { if(token != NULL) { //tokenizer(condition,lol,token); prev_and = false; } else {} } } else if(condition == semi_c && !prev_or) { if(run_execvp(lol)); prev_or = false; prev_and = true; } else { if(run_execvp(lol)); } } break; } } return 0; } <|endoftext|>
<commit_before>/* * LynxBot: a Twitch.tv IRC bot for Old School Runescape * Copyright (C) 2016 Alexei Frolov */ #include <cpr/cpr.h> #include <cstdio> #include <cstring> #include <fstream> #include <iostream> #include <regex> #include <string> #include <utils.h> #include "config.h" #include "lynxbot.h" #include "option.h" #include "TwitchBot.h" #ifdef __linux__ # include <sys/types.h> # include <sys/wait.h> # include <unistd.h> #endif /* LynxBot authorization URL */ static const char *AUTH_URL = "https://api.twitch.tv/kraken/oauth2/" "authorize?response_type=token&client_id=kkjhmekkzbepq0pgn34g671y5nexap8&" "redirect_uri=https://frolv.github.io/lynxbot/twitchauthconfirm.html&" "scope=channel_editor+channel_subscriptions+channel_check_subscription"; /* github api for latest release */ static const char *RELEASE_API = "https://api.github.com/repos/frolv/lynxbot/releases/latest"; struct botset { std::string name; /* twitch username of bot */ std::string channel; /* channel to join */ std::string pass; /* oauth token for account */ std::string access_token; /* access token for user's twitch */ }; void checkupdates(); void launchBot(struct botset *b, ConfigReader *cfgr); void twitchAuth(struct botset *b); bool authtest(const std::string &token, std::string &user); #ifdef __linux__ static int open_linux(const char *url); #endif #ifdef _WIN32 static int open_win(const char *url); #endif /* LynxBot: a Twitch.tv IRC bot for Old School Runescape */ int main(int argc, char **argv) { struct botset b; std::string path; int update; update = 1; int c; static struct l_option long_opts[] = { { "help", NO_ARG, 'h' }, { "no-check-update", NO_ARG, 'n' }, { "version", NO_ARG, 'v' }, { 0, 0, 0 } }; opt_init(); while ((c = l_getopt_long(argc, argv, "hv", long_opts)) != EOF) { switch (c) { case 'h': printf("usage: lynxbot [CHANNEL]\n%s - A Twitch.tv IRC " "bot for Old School Runescape\n" "Documentation can be found at %s\n", BOT_NAME, BOT_WEBSITE); return 0; case 'n': update = 0; break; case 'v': printf("%s %s\nCopyright (C) 2016 Alexei Frolov\n" "This program is distributed as free " "software\nunder the terms of the MIT " "License.\n", BOT_NAME, BOT_VERSION); return 0; case '?': fprintf(stderr, "%s\n", l_opterr()); fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; default: fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; } } if (argc - l_optind > 1) { fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; } /* check if a new version is available */ if (update) checkupdates(); /* read the config file */ path = utils::configdir() + utils::config("config"); ConfigReader cfgr(path); if (!cfgr.read()) { WAIT_INPUT(); return 1; } b.name = cfgr.get("name"); b.channel = cfgr.get("channel"); b.pass = cfgr.get("password"); b.access_token = cfgr.get("twitchtok"); /* authenticate with twitch */ if (b.access_token == "UNSET") { twitchAuth(&b); cfgr.set("twitchtok", b.access_token); cfgr.write(); } /* overwrite channel with arg */ if (l_optind != argc) b.channel = argv[l_optind]; if (b.channel[0] != '#') b.channel = '#' + b.channel; launchBot(&b, &cfgr); return 0; } /* launchBot: start a TwitchBot instance */ void launchBot(struct botset *b, ConfigReader *cfgr) { TwitchBot bot(b->name.c_str(), b->channel.c_str(), b->pass.c_str(), b->access_token.c_str(), cfgr); if (bot.connect()) bot.server_loop(); } /* twitchAuth: interactively authorize LynxBot with a Twitch account */ void twitchAuth(struct botset *b) { char c; int status; std::string token, user; printf("In order for the $status command to work, %s must be authorized" " to update your Twitch channel settings.\nWould you " "like to authorize %s now? (y/n) ", BOT_NAME, BOT_NAME); while ((c = getchar()) != 'n' && c != 'y') ; if (c == 'n') { b->access_token = "NULL"; return; } #ifdef __linux__ status = open_linux(AUTH_URL); #endif #ifdef _WIN32 status = open_win(AUTH_URL); #endif if (status != 0) { fprintf(stderr, "Could not open web browser\nPlease navigate " "to the following URL manually:\n%s\n,", AUTH_URL); WAIT_INPUT(); } printf("The authorization URL has been opened in your browser. Sign in " "with your Twitch account and click \"Authorize\" to " "proceed.\n"); printf("After you have clicked \"Authorize\" you will be redirected to " "a webpage with an access token.\nEnter the access " "token here:\n"); while (token.empty()) std::getline(std::cin, token); if (authtest(token, user)) { b->access_token = token; printf("Welcome, %s!\n %s has successfully been authorized " "with your Twitch account.", user.c_str(), BOT_NAME); } else { printf("Invalid token. Authorization failed.\n"); } WAIT_INPUT(); } /* authtest: test access token validity */ bool authtest(const std::string &token, std::string &user) { Json::Value json; cpr::Response resp = cpr::Get(cpr::Url("https://api.twitch.tv/kraken"), cpr::Header{{ "Authorization", "OAuth " + token }}); Json::Reader reader; if (!reader.parse(resp.text, json)) return false; if (json["token"]["valid"].asBool()) { user = json["token"]["user_name"].asString(); return true; } return false; } /* check for new lynxbot version and prompt user to install */ void checkupdates() { static const char *accept = "application/vnd.github.v3+json"; cpr::Response resp; Json::Value js; Json::Reader reader; int c; if (strstr(BOT_VERSION, "-beta")) return; resp = cpr::Get(cpr::Url(RELEASE_API), cpr::Header{{ "Accept", accept }}); if (!reader.parse(resp.text, js)) return; if (strcmp(js["tag_name"].asCString(), BOT_VERSION) != 0) { printf("A new version of %s (%s) is available.\nWould you like " "to open the download page? (y/n)\n", BOT_NAME, js["tag_name"].asCString()); while ((c = getchar()) != 'y' && c != 'n') ; if (c == 'n') return; #ifdef __linux__ open_linux(js["html_url"].asCString()); #endif #ifdef _WIN32 open_win(js["html_url"].asCString()); #endif exit(0); } } #ifdef __linux__ /* open_linux: launch browser on linux systems */ static int open_linux(const char *url) { switch (fork()) { case -1: perror("fork"); exit(1); case 0: execl("/usr/bin/xdg-open", "xdg-open", url, (char *)NULL); perror("/usr/bin/xdg-open"); exit(1); default: int status; wait(&status); return status >> 8; } } #endif #ifdef _WIN32 /* open_win: launch browser on windows systems */ static int open_win(const char *url) { int i; i = (int)ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL); return i <= 32; } #endif <commit_msg>main: remove unnecessary includes<commit_after>/* * LynxBot: a Twitch.tv IRC bot for Old School Runescape * Copyright (C) 2016 Alexei Frolov */ #include <cpr/cpr.h> #include <iostream> #include <string> #include <string.h> #include <utils.h> #include "config.h" #include "lynxbot.h" #include "option.h" #include "TwitchBot.h" #ifdef __linux__ # include <sys/types.h> # include <sys/wait.h> # include <unistd.h> #endif /* LynxBot authorization URL */ static const char *AUTH_URL = "https://api.twitch.tv/kraken/oauth2/" "authorize?response_type=token&client_id=kkjhmekkzbepq0pgn34g671y5nexap8&" "redirect_uri=https://frolv.github.io/lynxbot/twitchauthconfirm.html&" "scope=channel_editor+channel_subscriptions+channel_check_subscription"; /* github api for latest release */ static const char *RELEASE_API = "https://api.github.com/repos/frolv/lynxbot/releases/latest"; struct botset { std::string name; /* twitch username of bot */ std::string channel; /* channel to join */ std::string pass; /* oauth token for account */ std::string access_token; /* access token for user's twitch */ }; void checkupdates(); void launchBot(struct botset *b, ConfigReader *cfgr); void twitchAuth(struct botset *b); bool authtest(const std::string &token, std::string &user); #ifdef __linux__ static int open_linux(const char *url); #endif #ifdef _WIN32 static int open_win(const char *url); #endif /* LynxBot: a Twitch.tv IRC bot for Old School Runescape */ int main(int argc, char **argv) { struct botset b; std::string path; int update; update = 1; int c; static struct l_option long_opts[] = { { "help", NO_ARG, 'h' }, { "no-check-update", NO_ARG, 'n' }, { "version", NO_ARG, 'v' }, { 0, 0, 0 } }; opt_init(); while ((c = l_getopt_long(argc, argv, "hv", long_opts)) != EOF) { switch (c) { case 'h': printf("usage: lynxbot [CHANNEL]\n%s - A Twitch.tv IRC " "bot for Old School Runescape\n" "Documentation can be found at %s\n", BOT_NAME, BOT_WEBSITE); return 0; case 'n': update = 0; break; case 'v': printf("%s %s\nCopyright (C) 2016 Alexei Frolov\n" "This program is distributed as free " "software\nunder the terms of the MIT " "License.\n", BOT_NAME, BOT_VERSION); return 0; case '?': fprintf(stderr, "%s\n", l_opterr()); fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; default: fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; } } if (argc - l_optind > 1) { fprintf(stderr, "usage: %s [CHANNEL]\n", argv[0]); return 1; } /* check if a new version is available */ if (update) checkupdates(); /* read the config file */ path = utils::configdir() + utils::config("config"); ConfigReader cfgr(path); if (!cfgr.read()) { WAIT_INPUT(); return 1; } b.name = cfgr.get("name"); b.channel = cfgr.get("channel"); b.pass = cfgr.get("password"); b.access_token = cfgr.get("twitchtok"); /* authenticate with twitch */ if (b.access_token == "UNSET") { twitchAuth(&b); cfgr.set("twitchtok", b.access_token); cfgr.write(); } /* overwrite channel with arg */ if (l_optind != argc) b.channel = argv[l_optind]; if (b.channel[0] != '#') b.channel = '#' + b.channel; launchBot(&b, &cfgr); return 0; } /* launchBot: start a TwitchBot instance */ void launchBot(struct botset *b, ConfigReader *cfgr) { TwitchBot bot(b->name.c_str(), b->channel.c_str(), b->pass.c_str(), b->access_token.c_str(), cfgr); if (bot.connect()) bot.server_loop(); } /* twitchAuth: interactively authorize LynxBot with a Twitch account */ void twitchAuth(struct botset *b) { char c; int status; std::string token, user; printf("In order for the $status command to work, %s must be authorized" " to update your Twitch channel settings.\nWould you " "like to authorize %s now? (y/n) ", BOT_NAME, BOT_NAME); while ((c = getchar()) != 'n' && c != 'y') ; if (c == 'n') { b->access_token = "NULL"; return; } #ifdef __linux__ status = open_linux(AUTH_URL); #endif #ifdef _WIN32 status = open_win(AUTH_URL); #endif if (status != 0) { fprintf(stderr, "Could not open web browser\nPlease navigate " "to the following URL manually:\n%s\n,", AUTH_URL); WAIT_INPUT(); } printf("The authorization URL has been opened in your browser. Sign in " "with your Twitch account and click \"Authorize\" to " "proceed.\n"); printf("After you have clicked \"Authorize\" you will be redirected to " "a webpage with an access token.\nEnter the access " "token here:\n"); while (token.empty()) std::getline(std::cin, token); if (authtest(token, user)) { b->access_token = token; printf("Welcome, %s!\n %s has successfully been authorized " "with your Twitch account.", user.c_str(), BOT_NAME); } else { printf("Invalid token. Authorization failed.\n"); } WAIT_INPUT(); } /* authtest: test access token validity */ bool authtest(const std::string &token, std::string &user) { Json::Value json; cpr::Response resp = cpr::Get(cpr::Url("https://api.twitch.tv/kraken"), cpr::Header{{ "Authorization", "OAuth " + token }}); Json::Reader reader; if (!reader.parse(resp.text, json)) return false; if (json["token"]["valid"].asBool()) { user = json["token"]["user_name"].asString(); return true; } return false; } /* check for new lynxbot version and prompt user to install */ void checkupdates() { static const char *accept = "application/vnd.github.v3+json"; cpr::Response resp; Json::Value js; Json::Reader reader; int c; if (strstr(BOT_VERSION, "-beta")) return; resp = cpr::Get(cpr::Url(RELEASE_API), cpr::Header{{ "Accept", accept }}); if (!reader.parse(resp.text, js)) return; if (strcmp(js["tag_name"].asCString(), BOT_VERSION) != 0) { printf("A new version of %s (%s) is available.\nWould you like " "to open the download page? (y/n)\n", BOT_NAME, js["tag_name"].asCString()); while ((c = getchar()) != 'y' && c != 'n') ; if (c == 'n') return; #ifdef __linux__ open_linux(js["html_url"].asCString()); #endif #ifdef _WIN32 open_win(js["html_url"].asCString()); #endif exit(0); } } #ifdef __linux__ /* open_linux: launch browser on linux systems */ static int open_linux(const char *url) { switch (fork()) { case -1: perror("fork"); exit(1); case 0: execl("/usr/bin/xdg-open", "xdg-open", url, (char *)NULL); perror("/usr/bin/xdg-open"); exit(1); default: int status; wait(&status); return status >> 8; } } #endif #ifdef _WIN32 /* open_win: launch browser on windows systems */ static int open_win(const char *url) { int i; i = (int)ShellExecute(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL); return i <= 32; } #endif <|endoftext|>
<commit_before>#include <algorithm> #include <string> #include <iostream> #include <cassert> #include "subsequences.hpp" using std::cout; using std::endl; using std::size_t; using std::array; using std::ostream; template<class SubsetsIterator> bool last_subset_causes_counterexample ( SubsetsIterator subsets_begin, SubsetsIterator subsets_end ) { auto last_it = subsets_end - 1; for(auto i = subsets_begin; i != subsets_end; ++i) { subset_t first_union = unite(*last_it, *i); for(auto j = subsets_begin; j != subsets_end; ++j) { for(auto k = j; k != subsets_end; ++k) { if(j == i && k == last_it) continue; subset_t second_union = unite(*j, *k); if(first_union == second_union) return true; } } } return false; } template<size_t ProblemSize, size_t CurrentIndex = 0> struct bruteforce_helper { template<class AllSubsetsIterator> static void doit ( AllSubsetsIterator all_begin, AllSubsetsIterator all_end, array<subset_t, ProblemSize>& currently_chosen_subsets ) { for(auto subset_it = all_begin; subset_it != all_end; ++subset_it) { currently_chosen_subsets[CurrentIndex] = *subset_it; if(!last_subset_causes_counterexample(currently_chosen_subsets.begin(), currently_chosen_subsets.begin() + CurrentIndex + 1)) bruteforce_helper<ProblemSize, CurrentIndex + 1>::doit(subset_it, all_end, currently_chosen_subsets); } } }; template<size_t ProblemSize> struct bruteforce_helper<ProblemSize, ProblemSize> { template<class AllSubsetsIterator> static void doit ( AllSubsetsIterator, AllSubsetsIterator, array<subset_t, ProblemSize>& currently_chosen_subsets ) { cout << "counterexample: \n"; for(subset_t subset : currently_chosen_subsets) { cout << " "; print_subset(subset, cout); cout << "\n"; } cout << "unions: \n"; for(auto i = currently_chosen_subsets.begin(); i != currently_chosen_subsets.end(); ++i) { for(auto j = i + 1; j != currently_chosen_subsets.end(); ++j) { cout << " "; print_subset(unite(*i, *j), cout); cout << "\n"; } } } }; template<size_t ProblemSize> void bruteforce() { static_assert(ProblemSize >= 1, ""); cout << "brute-forcing problem size " << ProblemSize << "...\n"; relevant_subsets_t<ProblemSize - 1> subsets = relevant_subsets<ProblemSize - 1>(); array<subset_t, ProblemSize> currently_chosen_subsets; currently_chosen_subsets.fill(0); bruteforce_helper<ProblemSize>::doit(subsets.begin(), subsets.end(), currently_chosen_subsets); } int main() { //bruteforce<2>(); //bruteforce<3>(); //bruteforce<4>(); //bruteforce<5>(); //bruteforce<6>(); //bruteforce<7>(); bruteforce<8>(); } <commit_msg>Make k variable<commit_after>#include <algorithm> #include <string> #include <iostream> #include <cassert> #include "subsequences.hpp" using std::cout; using std::endl; using std::size_t; using std::array; using std::ostream; template<class SubsetsIterator> bool last_subset_causes_counterexample ( SubsetsIterator subsets_begin, SubsetsIterator subsets_end ) { auto last_it = subsets_end - 1; for(auto i = subsets_begin; i != subsets_end; ++i) { subset_t first_union = unite(*last_it, *i); for(auto j = subsets_begin; j != subsets_end; ++j) { for(auto k = j; k != subsets_end; ++k) { if(j == i && k == last_it) continue; subset_t second_union = unite(*j, *k); if(first_union == second_union) return true; } } } return false; } template<size_t N, size_t K, size_t CurrentIndex = 0> struct bruteforce_helper { template<class AllSubsetsIterator> static void doit ( AllSubsetsIterator all_begin, AllSubsetsIterator all_end, array<subset_t, K>& currently_chosen_subsets ) { for(auto subset_it = all_begin; subset_it != all_end; ++subset_it) { currently_chosen_subsets[CurrentIndex] = *subset_it; if(!last_subset_causes_counterexample(currently_chosen_subsets.begin(), currently_chosen_subsets.begin() + CurrentIndex + 1)) bruteforce_helper<N, K, CurrentIndex + 1>::doit(subset_it + 1, all_end, currently_chosen_subsets); } } }; template<size_t N, size_t K> struct bruteforce_helper<N, K, K> { template<class AllSubsetsIterator> static void doit ( AllSubsetsIterator, AllSubsetsIterator, array<subset_t, K>& currently_chosen_subsets ) { cout << "counterexample: \n"; for(subset_t subset : currently_chosen_subsets) { cout << " "; print_subset(subset, cout); cout << "\n"; } cout << "unions: \n"; for(auto i = currently_chosen_subsets.begin(); i != currently_chosen_subsets.end(); ++i) { for(auto j = i + 1; j != currently_chosen_subsets.end(); ++j) { cout << " "; print_subset(unite(*i, *j), cout); cout << "\n"; } } } }; template<size_t N, size_t K> void bruteforce() { cout << "brute-forcing N=" << N<< " " << "K=" << K << endl; relevant_subsets_t<N> subsets = relevant_subsets<N>(); array<subset_t, K> currently_chosen_subsets; currently_chosen_subsets.fill(0); bruteforce_helper<N, K>::doit(subsets.begin(), subsets.end(), currently_chosen_subsets); } int main() { //volatile size_t i = 0; //for(size_t j = 0; j != 100000000000; ++j) // ++i; //bruteforce<2, 3>(); //bruteforce<4, 5>(); //bruteforce<5, 6>(); //bruteforce<6, 7>(); //bruteforce<6, 8>(); //bruteforce<7, 10>(); //bruteforce<7, 9>(); //bruteforce<7, 10>(); bruteforce<9, 12>(); } <|endoftext|>
<commit_before>#include <Refal2.h> using namespace Refal2; //----------------------------------------------------------------------------- // Constants const char* const UtilityName = "refal2"; //----------------------------------------------------------------------------- // CCommandLineOptions typedef std::vector<std::string> CFileNames; class CCommandLineOptions { public: CCommandLineOptions() { ResetDefaults(); } void ResetDefaults(); bool SetByCommandLineArguments( int numberOfArguments, const char* const arguments[] ); bool IsCheckOnly() const { return isCheckOnly; } void SetCheckOnly( bool _isCheckOnly = true ) { isCheckOnly = _isCheckOnly; } bool IsInfoOnly() const { return isInfoOnly; } void SetInfoOnly( bool _isInfoOnly = true ) { isInfoOnly = _isInfoOnly; } void ResetSourceFiles() { sourceFiles.clear(); } bool HasSourceFiles() const { return !sourceFiles.empty(); } CFileNames SourceFiles() const { return sourceFiles; } void AddSourceFile( const std::string& fileName ) { sourceFiles.push_back( fileName ); } private: bool isInfoOnly; bool optionsEnd; // if true program only parse and print found errors bool isCheckOnly; // *.ref files CFileNames sourceFiles; static bool isOption( const std::string& argument ); bool parseArgument( const std::string& argument ); static void printInvalidOption( const std::string& argument ); static void printHelp(); static void printVersion(); }; //----------------------------------------------------------------------------- void CCommandLineOptions::ResetDefaults() { SetInfoOnly( false ); SetCheckOnly( false ); ResetSourceFiles(); } bool CCommandLineOptions::SetByCommandLineArguments( int numberOfArguments, const char* const arguments[] ) { ResetDefaults(); optionsEnd = false; for( int i = 0; i < numberOfArguments; i++ ) { if( !parseArgument( arguments[i] ) ) { ResetDefaults(); return false; } if( IsInfoOnly() ) { break; } } return true; } bool CCommandLineOptions::isOption( const std::string& argument ) { return ( argument.length() >= 2 && argument.front() == '-' ); } bool CCommandLineOptions::parseArgument( const std::string& argument ) { if( !optionsEnd && isOption( argument ) ) { if( argument == "-c" || argument == "--check" ) { SetCheckOnly(); } else if( argument == "--help" ) { SetInfoOnly(); printHelp(); } else if( argument == "--version" ) { SetInfoOnly(); printVersion(); } else if( argument == "--" ) { optionsEnd = true; } else { printInvalidOption( argument ); return false; } } else if( !argument.empty() ) { AddSourceFile( argument ); } return true; } void CCommandLineOptions::printInvalidOption( const std::string& argument ) { std::cerr << UtilityName << ": invalid option `" << argument << "`" << std::endl << "Try `" << UtilityName << " --help` for more information." << std::endl; } void CCommandLineOptions::printHelp() { std::cout << "Usage: " << UtilityName << " [OPTION]... [FILE]..." << std::endl << std::endl << " -c, --check check source FILE(s) for errors and exit" << std::endl << " --help display this help and exit" << std::endl << " --version output version information and exit" << std::endl << std::endl << "Report bugs to <refal2@yandex.ru>." << std::endl; } void CCommandLineOptions::printVersion() { std::cout << "Written by Anton Todua." << std::endl << "Report bugs to <refal2@yandex.ru>" << std::endl; } //----------------------------------------------------------------------------- // CSourceFilesProcessor class CSourceFilesProcessor : private IErrorHandler { public: static CProgramPtr Compile( const CFileNames& fileNames ); static bool Check( const CFileNames& fileNames ); private: CScanner scanner; std::ifstream file; CSourceFilesProcessor( const CFileNames& fileNames ); CSourceFilesProcessor( const CSourceFilesProcessor& ); CSourceFilesProcessor& operator=( const CSourceFilesProcessor& ); void processFile( const std::string& fileName ); virtual void Error( const CError& error ); }; //----------------------------------------------------------------------------- CProgramPtr CSourceFilesProcessor::Compile( const CFileNames& fileNames ) { CSourceFilesProcessor sourceFilesProcessor( fileNames ); return sourceFilesProcessor.scanner.BuildProgram(); } bool CSourceFilesProcessor::Check( const CFileNames& fileNames ) { CSourceFilesProcessor sourceFilesProcessor( fileNames ); return sourceFilesProcessor.scanner.CheckProgram(); } CSourceFilesProcessor::CSourceFilesProcessor( const CFileNames& fileNames ) { scanner.SetErrorHandler( this ); if( fileNames.empty() ) { for( char c; std::cin.get( c ); ) { scanner.AddChar( c ); } if( scanner.ErrorSeverity() != ES_FatalError ) { scanner.AddEndOfFile(); } } else { for( CFileNames::const_iterator fileName = fileNames.begin(); fileName != fileNames.end(); ++fileName ) { processFile( *fileName ); if( scanner.ErrorSeverity() == ES_FatalError ) { break; } } } } void CSourceFilesProcessor::processFile( const std::string& fileName ) { file.open( fileName ); if( file.good() ) { scanner.SetFileName( fileName ); for( char c; file.get( c ); ) { scanner.AddChar( c ); } if( scanner.ErrorSeverity() != ES_FatalError ) { scanner.AddEndOfFile(); } } else { scanner.SetFileName( UtilityName ); scanner.RaiseError( ES_FatalError, "no such file" ); scanner.ResetFileName(); } } void CSourceFilesProcessor::Error( const CError& error ) { std::cerr << error.UserMessage() << std::endl; if( error.Severity() == ES_FatalError ) { file.clear( std::ios_base::eofbit ); std::cin.clear( std::ios_base::eofbit ); } } //----------------------------------------------------------------------------- const char* const ExecutionResultStrings[] = { "ok", "recognition impossible", "call empty function", "lost function label", "wrong argument of embedded function" }; const std::string SeparatorLine( 80, '-' ); enum TReturnCode { RC_OK = 0, RC_InvalidOptions = 1, RC_ErrorsInSourceFiles = 2, RC_RuntimeError = 3 }; int main( int argc, const char* argv[] ) { std::ios::sync_with_stdio( false ); CCommandLineOptions commandLineOptions; if( !commandLineOptions.SetByCommandLineArguments( argc - 1, argv + 1 ) ) { return RC_InvalidOptions; } if( commandLineOptions.IsInfoOnly() ) { return RC_OK; } if( commandLineOptions.IsCheckOnly() ) { if( CSourceFilesProcessor::Check( commandLineOptions.SourceFiles() ) ) { return RC_OK; } return RC_ErrorsInSourceFiles; } CProgramPtr program = CSourceFilesProcessor::Compile( commandLineOptions.SourceFiles() ); if( !static_cast<bool>( program ) ) { return RC_ErrorsInSourceFiles; } CReceptaclePtr receptacle( new CReceptacle ); CUnitList fieldOfView; CUnitNode* errorNode = nullptr; TExecutionResult result = ER_OK; try { result = COperationsExecuter::Run( program, receptacle, fieldOfView, errorNode ); } catch( std::bad_alloc& e ) { std::cerr << "Not enough memory `" << e.what() << "`," << std::endl << "Check your program for infinite recursion." << std::endl; return RC_RuntimeError; } std::cout << SeparatorLine << std::endl; std::cout << "Execution result: " << ExecutionResultStrings[result] << "." << std::endl; if( !fieldOfView.IsEmpty() ) { std::cout << "Field of view: " << std::endl; CProgramPrintHelper programPrintHelper( program ); //programPrintHelper.SetPrintLabelWithModule(); fieldOfView.HandyPrint( std::cout, programPrintHelper ); } if( !receptacle->IsEmpty() ) { if( !fieldOfView.IsEmpty() ) { std::cout << SeparatorLine << std::endl; } std::cout << "Receptacle: " << std::endl; CUnitList receptacleUnitList; receptacle->DigOutAll( receptacleUnitList ); CProgramPrintHelper programPrintHelper( program ); receptacleUnitList.HandyPrint( std::cout, programPrintHelper ); std::cout << std::endl; } return RC_OK; } <commit_msg>fix seriously error with openning few files<commit_after>#include <Refal2.h> using namespace Refal2; //----------------------------------------------------------------------------- // Constants const char* const UtilityName = "refal2"; //----------------------------------------------------------------------------- // CCommandLineOptions typedef std::vector<std::string> CFileNames; class CCommandLineOptions { public: CCommandLineOptions() { ResetDefaults(); } void ResetDefaults(); bool SetByCommandLineArguments( int numberOfArguments, const char* const arguments[] ); bool IsCheckOnly() const { return isCheckOnly; } void SetCheckOnly( bool _isCheckOnly = true ) { isCheckOnly = _isCheckOnly; } bool IsInfoOnly() const { return isInfoOnly; } void SetInfoOnly( bool _isInfoOnly = true ) { isInfoOnly = _isInfoOnly; } void ResetSourceFiles() { sourceFiles.clear(); } bool HasSourceFiles() const { return !sourceFiles.empty(); } CFileNames SourceFiles() const { return sourceFiles; } void AddSourceFile( const std::string& fileName ) { sourceFiles.push_back( fileName ); } private: bool isInfoOnly; bool optionsEnd; // if true program only parse and print found errors bool isCheckOnly; // *.ref files CFileNames sourceFiles; static bool isOption( const std::string& argument ); bool parseArgument( const std::string& argument ); static void printInvalidOption( const std::string& argument ); static void printHelp(); static void printVersion(); }; //----------------------------------------------------------------------------- void CCommandLineOptions::ResetDefaults() { SetInfoOnly( false ); SetCheckOnly( false ); ResetSourceFiles(); } bool CCommandLineOptions::SetByCommandLineArguments( int numberOfArguments, const char* const arguments[] ) { ResetDefaults(); optionsEnd = false; for( int i = 0; i < numberOfArguments; i++ ) { if( !parseArgument( arguments[i] ) ) { ResetDefaults(); return false; } if( IsInfoOnly() ) { break; } } return true; } bool CCommandLineOptions::isOption( const std::string& argument ) { return ( argument.length() >= 2 && argument.front() == '-' ); } bool CCommandLineOptions::parseArgument( const std::string& argument ) { if( !optionsEnd && isOption( argument ) ) { if( argument == "-c" || argument == "--check" ) { SetCheckOnly(); } else if( argument == "--help" ) { SetInfoOnly(); printHelp(); } else if( argument == "--version" ) { SetInfoOnly(); printVersion(); } else if( argument == "--" ) { optionsEnd = true; } else { printInvalidOption( argument ); return false; } } else if( !argument.empty() ) { AddSourceFile( argument ); } return true; } void CCommandLineOptions::printInvalidOption( const std::string& argument ) { std::cerr << UtilityName << ": invalid option `" << argument << "`" << std::endl << "Try `" << UtilityName << " --help` for more information." << std::endl; } void CCommandLineOptions::printHelp() { std::cout << "Usage: " << UtilityName << " [OPTION]... [FILE]..." << std::endl << std::endl << " -c, --check check source FILE(s) for errors and exit" << std::endl << " --help display this help and exit" << std::endl << " --version output version information and exit" << std::endl << std::endl << "Report bugs to <refal2@yandex.ru>." << std::endl; } void CCommandLineOptions::printVersion() { std::cout << "Written by Anton Todua." << std::endl << "Report bugs to <refal2@yandex.ru>" << std::endl; } //----------------------------------------------------------------------------- // CSourceFilesProcessor class CSourceFilesProcessor : private IErrorHandler { public: static CProgramPtr Compile( const CFileNames& fileNames ); static bool Check( const CFileNames& fileNames ); private: CScanner scanner; std::ifstream file; CSourceFilesProcessor( const CFileNames& fileNames ); CSourceFilesProcessor( const CSourceFilesProcessor& ); CSourceFilesProcessor& operator=( const CSourceFilesProcessor& ); void processFile( const std::string& fileName ); virtual void Error( const CError& error ); }; //----------------------------------------------------------------------------- CProgramPtr CSourceFilesProcessor::Compile( const CFileNames& fileNames ) { CSourceFilesProcessor sourceFilesProcessor( fileNames ); return sourceFilesProcessor.scanner.BuildProgram(); } bool CSourceFilesProcessor::Check( const CFileNames& fileNames ) { CSourceFilesProcessor sourceFilesProcessor( fileNames ); return sourceFilesProcessor.scanner.CheckProgram(); } CSourceFilesProcessor::CSourceFilesProcessor( const CFileNames& fileNames ) { scanner.SetErrorHandler( this ); if( fileNames.empty() ) { for( char c; std::cin.get( c ); ) { scanner.AddChar( c ); } if( scanner.ErrorSeverity() != ES_FatalError ) { scanner.AddEndOfFile(); } } else { for( CFileNames::const_iterator fileName = fileNames.begin(); fileName != fileNames.end(); ++fileName ) { processFile( *fileName ); if( scanner.ErrorSeverity() == ES_FatalError ) { break; } } } } void CSourceFilesProcessor::processFile( const std::string& fileName ) { file.open( fileName ); scanner.SetFileName( fileName ); if( file.good() ) { for( char c; file.get( c ); ) { scanner.AddChar( c ); } if( scanner.ErrorSeverity() != ES_FatalError ) { scanner.AddEndOfFile(); } } else { scanner.RaiseError( ES_FatalError, "no such file" ); } scanner.ResetFileName(); file.close(); } void CSourceFilesProcessor::Error( const CError& error ) { std::cerr << error.UserMessage() << std::endl; if( error.Severity() == ES_FatalError ) { file.clear( std::ios_base::eofbit ); std::cin.clear( std::ios_base::eofbit ); } } //----------------------------------------------------------------------------- const char* const ExecutionResultStrings[] = { "ok", "recognition impossible", "call empty function", "lost function label", "wrong argument of embedded function" }; const std::string SeparatorLine( 80, '-' ); enum TReturnCode { RC_OK = 0, RC_InvalidOptions = 1, RC_ErrorsInSourceFiles = 2, RC_RuntimeError = 3 }; int main( int argc, const char* argv[] ) { std::ios::sync_with_stdio( false ); CCommandLineOptions commandLineOptions; if( !commandLineOptions.SetByCommandLineArguments( argc - 1, argv + 1 ) ) { return RC_InvalidOptions; } if( commandLineOptions.IsInfoOnly() ) { return RC_OK; } if( commandLineOptions.IsCheckOnly() ) { if( CSourceFilesProcessor::Check( commandLineOptions.SourceFiles() ) ) { return RC_OK; } return RC_ErrorsInSourceFiles; } CProgramPtr program = CSourceFilesProcessor::Compile( commandLineOptions.SourceFiles() ); if( !static_cast<bool>( program ) ) { return RC_ErrorsInSourceFiles; } CReceptaclePtr receptacle( new CReceptacle ); CUnitList fieldOfView; CUnitNode* errorNode = nullptr; TExecutionResult result = ER_OK; try { result = COperationsExecuter::Run( program, receptacle, fieldOfView, errorNode ); } catch( std::bad_alloc& e ) { std::cerr << "Not enough memory `" << e.what() << "`," << std::endl << "Check your program for infinite recursion." << std::endl; return RC_RuntimeError; } std::cout << SeparatorLine << std::endl; std::cout << "Execution result: " << ExecutionResultStrings[result] << "." << std::endl; if( !fieldOfView.IsEmpty() ) { std::cout << "Field of view: " << std::endl; CProgramPrintHelper programPrintHelper( program ); //programPrintHelper.SetPrintLabelWithModule(); fieldOfView.HandyPrint( std::cout, programPrintHelper ); } if( !receptacle->IsEmpty() ) { if( !fieldOfView.IsEmpty() ) { std::cout << SeparatorLine << std::endl; } std::cout << "Receptacle: " << std::endl; CUnitList receptacleUnitList; receptacle->DigOutAll( receptacleUnitList ); CProgramPrintHelper programPrintHelper( program ); receptacleUnitList.HandyPrint( std::cout, programPrintHelper ); std::cout << std::endl; } return RC_OK; } <|endoftext|>
<commit_before>// // main.cpp // game_of_life // // Created by Chris Powell on 8/24/13. // Copyright (c) 2013 Prylis Inc. All rights reserved. // http://github.com/cpowell/game_of_life // You can redistribute and/or modify this software only in accordance with // the terms found in the "LICENSE" file included with the source code. // #include <iostream> #include <chrono> #include <thread> #include "board.h" // Forward declaration void swapBoards(Board&, Board&); int main() { // There are two boards defined; the one "in back" is updated based // on the current status of the one "in front", then brought to the // front. Efficient, and kind to memory. Board flip, flop; // Seed the RNG and set up a random smattering of live cells. srand((unsigned int) time(NULL)); flip.randomize(20); // This routine evolves and prints the board forever; you must // terminate the program. while (true) { flop.evolve(flip); // To see the Intel TBB parallelism at work, comment out these // next two lines to let the program run unfettered. It will // maximize your available cores. flop.print(); // std::this_thread::sleep_for(std::chrono::milliseconds(150)); swapBoards(flip, flop); } return 0; } /** A textbook 'swap' function using pass-by-reference. @param one is a reference to the first board @param two is a reference to the second board */ void swapBoards(Board &one, Board &two) { Board temp = one; one = two; two = temp; } <commit_msg>Use std::swap here.<commit_after>// // main.cpp // game_of_life // // Created by Chris Powell on 8/24/13. // Copyright (c) 2013 Prylis Inc. All rights reserved. // http://github.com/cpowell/game_of_life // You can redistribute and/or modify this software only in accordance with // the terms found in the "LICENSE" file included with the source code. // #include <iostream> #include <chrono> #include <thread> #include "board.h" int main() { // There are two boards defined; the one "in back" is updated based // on the current status of the one "in front", then brought to the // front. Efficient, and kind to memory. Board flip, flop; // Seed the RNG and set up a random smattering of live cells. srand((unsigned int) time(NULL)); flip.randomize(20); // This routine evolves and prints the board forever; you must // terminate the program. while (true) { flop.evolve(flip); // To see the Intel TBB parallelism at work, comment out these // next two lines to let the program run unfettered. It will // maximize your available cores. flop.print(); // std::this_thread::sleep_for(std::chrono::milliseconds(150)); std::swap(flip, flop); } return 0; } <|endoftext|>
<commit_before>#include "cmd.h" #include <iostream> #include <cstdlib> #include <string> #include <cstring> #include <unistd.h> #include <stdio.h> #include <vector> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <pwd.h> #include <queue> #include <fcntl.h> #include <sys/stat.h> using namespace std; //echo a || echo b && echo c || echo d //echo a || echo b && echo c && echo d // g++ -g -Wall -Werror -ansi -pedantic main.cpp bool exec(cmd c); void runPrep(cmd &c); void run(queue<cmd> &commands, queue<string> &connectors); bool redirectOut(queue<cmd> &commands, queue<string> &connectors) { //if there's no file passed in, do nothing if(commands.size() < 2) return false; cmd currCmd = commands.front(); commands.pop(); char * file_name = commands.front().toArray()[0]; //cout << "Printing into: " << file_name << endl; // 0 = cin // 1 = cout // 2 = cerr int fl; int stdout = dup(1); if(stdout == -1){ perror("There was an error with dup()"); exit(1); } if(close(1) == -1){ perror("There was an error with close()"); exit(1); } fl = open(file_name, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR); if (fl == -1){ perror("There was an error with open()"); exit(1); } //from now on everything is going to be printed into the file bool ret = exec(currCmd); if(close(fl) == -1){ perror("There was an error with close(). "); exit(1); } if(dup2(stdout, 1) == -1){ perror("There was an error with dup2()"); exit(1); } if(!commands.empty())commands.pop(); if(!connectors.empty())connectors.pop(); return ret; } // runs fork and execvp returning true if execvp succeed bool exec(cmd c) { int status; int pid = fork(); if(pid == -1){//fork’s return value for an error is -1 perror("There was an error with fork()"); exit(1);//there was an error with fork so exit the program and go back and fix it } else if(pid == 0){//when pid is 0 you are in the child process //This is the child process char **argv = c.toArray(); if(-1 == execvp(*argv, argv)) perror("There was an error in execvp()"); exit(1); } //if pid is not 0 then we’re in the parent //parent process else{ pid = wait(&status); if(pid == -1){ perror("There was an error in wait()"); exit(1); } if(WIFEXITED(status)){ if(WEXITSTATUS(status) > 0)return false; return true; } } return false; } // aux run() by spliting the root command void runPrep(cmd &c) { queue<cmd> commands; queue<string> connectors; //split commands using connectors an put them onto a queue commands = c.split(connectors); run(commands, connectors); } // do the logics of commands, executing execpv when needed // then call run again recursively // or exits the program if it's the case void run(queue<cmd> &commands, queue<string> &connectors) { if(commands.empty()) return; //if the next connector in queue is a redirectOut output if(connectors.front()== ">"){ redirectOut(commands, connectors); run(commands, connectors); return; } //use the first command "highest priority" string con; if(!connectors.empty())con= connectors.front(); cmd com = commands.front(); commands.pop(); // execpv and fork process // cout << "_"<< com.toString() << "_"<< endl; // cout << "c " << con << "_" << endl; if(com.toString() == "exit") exit(0); bool ok = exec(com); if(ok){ //SUCESS if(con == "||" ){ if(!connectors.empty())connectors.pop(); if(!commands.empty())commands.pop(); } else if(con == "&&" || con == ";"){ if(!connectors.empty())connectors.pop(); } } else { //FAIL if(con == "&&"){ if(!connectors.empty())connectors.pop(); if(!commands.empty())commands.pop(); } else if(con == "||" || con == ";"){ if(!connectors.empty())connectors.pop(); } } run(commands, connectors); return ; } // returns a string with user and machine name string getPrompt(){ char machine[128]; string user; string prompt; struct passwd *pw = getpwuid(getuid()); int host = gethostname(machine,128); if(pw != NULL && host != -1){ user = pw->pw_name; prompt = user + "@" + string(machine) + "$ "; } else{ prompt = "$ "; if(pw == NULL) perror("There was an error in getpwuid()"); if(host == -1) perror("There was an error in gethostname()"); } return prompt; } // main program // get input until in a infinite loop // within functions are responsible for exiting the program int main() { while(true){ cout << getPrompt(); string st; getline (cin,st); if(st == "exit") exit(0); if(st.empty() || st == "#") continue; cmd c(st); runPrep(c); } return 0; } <commit_msg>output redirect for more than 1 cmd<commit_after>#include "cmd.h" #include <iostream> #include <cstdlib> #include <string> #include <cstring> #include <unistd.h> #include <stdio.h> #include <vector> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <pwd.h> #include <queue> #include <fcntl.h> #include <sys/stat.h> using namespace std; //echo a || echo b && echo c || echo d //echo a || echo b && echo c && echo d // echo aaa > a; echo bbb > b && echo ccc > c // echo aaa> a; echo bbb >b && echo ccc> c // g++ -g -Wall -Werror -ansi -pedantic main.cpp bool exec(cmd c); void runPrep(cmd &c); void run(queue<cmd> &commands, queue<string> &connectors); bool redirectOut(queue<cmd> &commands, queue<string> &connectors) { //cout << "_red_"<< endl; //if there's no file passed in, do nothing if(commands.size() < 2) return false; cmd currCmd = commands.front(); commands.pop(); cout << commands.front().toString() <<endl; char * file_name = commands.front().toArray()[0]; cout << "Printing into: " << file_name << endl; // 0 = cin // 1 = cout // 2 = cerr int fl; int stdout = dup(1); if(stdout == -1){ perror("There was an error with dup()"); exit(1); } if(close(1) == -1){ perror("There was an error with close()"); exit(1); } fl = open(file_name, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR); if (fl == -1){ perror("There was an error with open()"); exit(1); } //from now on everything is going to be printed into the file //cout << "_"<< currCmd.toString() << "_"<< endl; bool ret = exec(currCmd); if(close(fl) == -1){ perror("There was an error with close(). "); exit(1); } if(dup2(stdout, 1) == -1){ perror("There was an error with dup2()"); exit(1); } //if(!commands.empty())commands.pop(); if(!connectors.empty())connectors.pop(); return ret; } // runs fork and execvp returning true if execvp succeed bool exec(cmd c) { //cout<< c.toString() << endl; int status; int pid = fork(); if(pid == -1){//fork’s return value for an error is -1 perror("There was an error with fork()"); exit(1);//there was an error with fork so exit the program and go back and fix it } else if(pid == 0){//when pid is 0 you are in the child process //This is the child process char **argv = c.toArray(); if(-1 == execvp(*argv, argv)){ perror("There was an error in execvp()"); } exit(1); } //if pid is not 0 then we’re in the parent //parent process else{ pid = wait(&status); if(pid == -1){ perror("There was an error in wait()"); exit(1); } if(WIFEXITED(status)){ if(WEXITSTATUS(status) > 0)return false; return true; } } return false; } // aux run() by spliting the root command void runPrep(cmd &c) { queue<cmd> commands; queue<string> connectors; //split commands using connectors an put them onto a queue commands = c.split(connectors); run(commands, connectors); } // do the logics of commands, executing execpv when needed // then call run again recursively // or exits the program if it's the case void run(queue<cmd> &commands, queue<string> &connectors) { if(commands.empty()) return; //use the first command "highest priority" cmd com = commands.front(); if(com.toString() == "exit") exit(0); string con; if(!connectors.empty())con= connectors.front(); cout << "_"<< com.toString() << "_"<< endl; cout << "-" << con << "-" << endl; bool ok; //if the next connector in queue is a redirectOut output if(!con.empty() && con== ">"){ ok = redirectOut(commands, connectors); } else { ok = exec(com); } commands.pop(); if(!connectors.empty())con= connectors.front(); if(ok){ //SUCESS if(con == "||" ){ if(!connectors.empty())connectors.pop(); if(!commands.empty())commands.pop(); } else if(con == "&&" || con == ";"){ if(!connectors.empty())connectors.pop(); } } else { //FAIL if(con == "&&"){ if(!connectors.empty())connectors.pop(); if(!commands.empty())commands.pop(); } else if(con == "||" || con == ";"){ if(!connectors.empty())connectors.pop(); } } run(commands, connectors); return ; } // returns a string with user and machine name string getPrompt(){ char machine[128]; string user; string prompt; struct passwd *pw = getpwuid(getuid()); int host = gethostname(machine,128); if(pw != NULL && host != -1){ user = pw->pw_name; prompt = user + "@" + string(machine) + "$ "; } else{ prompt = "$ "; if(pw == NULL) perror("There was an error in getpwuid()"); if(host == -1) perror("There was an error in gethostname()"); } return prompt; } // main program // get input until in a infinite loop // within functions are responsible for exiting the program int main() { while(true){ cout << getPrompt(); string st; getline (cin,st); if(st == "exit") exit(0); if(st.empty() || st == "#") continue; cmd c(st); runPrep(c); } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <cstdint> #include <algorithm> #include <memory> #include <stdio.h> #include <chrono> #include "config.hpp" // Machine core #include <dcpu_opcodes.hpp> #include <dcpu.hpp> // Devices #include <devices/gclock.hpp> #include <devices/gkeyboard.hpp> #include <devices/lem1802.hpp> #include <devices/lem1803.hpp> #include <devices/cgm.hpp> #include <devices/speaker.hpp> // Audio #include <audio/square_gen.hpp> // Util #include <disassembler.hpp> #include <binasm.hpp> using namespace cpu; void print_help(std::string program_name) { std::cout << "usage : " << program_name << " [-options] <dcpu16-exe>\n"; std::cout << "--------------------------------------------------------\n"; std::cout << " options:" << std::endl; std::cout << " -assemble (-a) : assemble before load (experimental)\n"; std::cout << " -debug (-d) : start in debug mode\n"; std::cout << " F1 : next step" << std::endl; std::cout << " F2 : print registers" << std::endl; std::cout << " F3 : reset (no need debug mode)" << std::endl; std::cout << " F12 : switch debug/run" << std::endl; std::cout << " --monitor=<monitor_name> : use the following monitor\n"; std::cout << " 1802 -> Lem1802 (default) [c] (-1802)\n"; std::cout << " 1803 -> Lem1803 [c] (-1803)" << std::endl; std::cout << " cgm -> Colour Graphics Monitor (-cgm)\n"; std::cout << " [c] : compatible with Lem1802 0x10c programs\n"; std::cout << " -output <filename> (-o) : output assembled filename\n"; std::cout << " -time (-t) : use timed emulation (else refresh based)\n"; std::cout << " -vsync (-v) : use vertical synchronisation\n"; std::cout << " (more accurate but may bug)\n"; } int main (int argc, char **argv) { std::string filename; std::string outname="a.out"; //output assembled filename int monitor_type=0; bool debug=false; //use vsync for refresh the screen (more accuracte than setFrameLimit) bool use_vsync=false; //use time emulation based on sf::Clock; bool use_time=false; //need asssemble the file bool assemble=false; //TODO make a fonction that parse argument into a program struct for (int k=1; k < argc; k++) //parse arguments { if (argv[k][0] == '-') { std::string opt = argv[k]; if (opt=="--help"||opt=="-help"||opt=="-h") { std::string pn = argv[0]; pn.erase(0,pn.find_last_of('\\')+1); //windows pn.erase(0,pn.find_last_of('/')+1); //linux print_help(pn); return 0; } else if (opt=="-debug") debug=true; else if (opt=="-1802"||opt=="--monitor=1802") monitor_type=0; else if (opt=="-1803"||opt=="--monitor=1803") monitor_type=1; else if (opt=="-cgm"||opt=="--monitor=cgm") monitor_type=2; else if (opt.find("--monitor") != std::string::npos) { std::cout << "warning: unknow monitor type "; std::cout << opt << std::endl; } else if (opt == "-vsync" || opt == "-v") use_vsync=true; else if (opt == "-time" || opt == "-t") use_time=true; else if (opt == "-assemble" || opt == "-a") assemble=true; else if ((opt == "-output" || opt == "-o") && argc > k+1) { assemble=true; outname = argv[k+1]; k++; } else if (opt == "-output" || opt == "-o") { std::cout << "warning: option " << opt << " requiert"; std::cout << " another argument it will be ignored here"; } else { std::cout << "warning: unknow option "; std::cout << opt << " it will be ignored !" << std::endl; } } else { filename = argv[k]; } } if (assemble) { BinAsm assembler; if (!assembler.load(filename)) return 0xdead; if (!assembler.assemble()) return 0xdead; if (!assembler.resolve_labels()) return 0xdead; if (!assembler.save(outname)) return 0xdead; filename = outname; } if (argc <= 1 || !filename.size()) { std::cerr <<"error: missing input file, type --help for list options\n"; return 0; } sf::String window_title="dcpu_vm"; auto dcpu = std::make_shared<DCPU>(); auto gclock = std::make_shared<Generic_Clock>(); auto gkeyboard = std::make_shared<keyboard::GKeyboard>(); // Prepare the speaker device auto speaker = std::make_shared<speaker::Speaker>(); audio::SquareGenerator gen; gen.prepare(44100); gen.play(); speaker->setFreqCallback(audio::SquareGenerator::WrappeCallback, (void *)(&gen)); // Sets apropiated monitor std::shared_ptr<AbstractMonitor> monitor; switch (monitor_type) { case 1: monitor=std::make_shared<lem::Lem1803>(); std::cout << "use Lem1803 Monitor" << std::endl; window_title = "Lem 1803"; break; case 2: monitor=std::make_shared<cgm::CGM>(); std::cout << "use CGM Monitor" << std::endl; window_title = "CGM"; break; default : monitor=std::make_shared<lem::Lem1802>(); std::cout << "use Lem1802 Monitor" << std::endl; window_title = "Lem 1802"; break; } dcpu->attachHardware (monitor); dcpu->attachHardware (gclock); dcpu->attachHardware (gkeyboard); dcpu->attachHardware (speaker); dcpu->reset(); dcpu->loadProgramFromFile(filename); sf::Texture texture; // texture of the screen sf::Sprite sprite; //sprite of the screen const sf::Image* screen = monitor->getScreen(); sf::Clock clock; sf::RenderWindow window; float border_add = monitor->borderSize()*2; window.create(sf::VideoMode(monitor->phyWidth()+border_add, monitor->phyHeight()+border_add), window_title); if (use_vsync) { std::cout << "warning: vsync activated may bug" << std::endl; window.setVerticalSyncEnabled(true); } else window.setFramerateLimit(50); // We try to use a window to show a fake keyboard and capture keyboard // events if it have focus sf::RenderWindow keyb_win; keyb_win.create(sf::VideoMode(484, 196), "Keyboard", sf::Style::Titlebar | sf::Style::Close); keyb_win.setKeyRepeatEnabled(false); keyb_win.setActive(false); sf::Texture keyb_tx; bool keyb_image_loaded = keyb_tx.loadFromFile("assets/keyb_img.png"); sf::Sprite keyb_sprite; if (keyb_image_loaded) keyb_sprite.setTexture(keyb_tx); else std::cerr << "Waring: assets/keyb_img.png not found !" << std::endl; bool keyb_focus; bool compensate_time = false; while (window.isOpen() && keyb_win.isOpen()) { //Because non mainthread event are forbidden in OSX // Process events sf::Event event; while (keyb_win.pollEvent(event)) { // This window capture key events to the VM window if have focus if (event.type == sf::Event::Closed) { keyb_win.close(); } else if (event.type == sf::Event::GainedFocus) { keyb_focus = true; } else if (event.type == sf::Event::LostFocus) { keyb_focus = false; } else if (keyb_focus && ( event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased || event.type == sf::Event::TextEntered )) { // Process VM keyboard input bool pressed = (event.type == sf::Event::KeyPressed); unsigned char keycode=0; // Note this works becuase Unicode maps ASCII 7 bit in his // first 128 codes if (event.type == sf::Event::TextEntered && ((event.text.unicode >= '!' && event.text.unicode <= '/') || (event.text.unicode >= ':' && event.text.unicode <= '@') || (event.text.unicode >= '[' && event.text.unicode <= 0x60) || (event.text.unicode >= '{' && event.text.unicode <= 0x7F) )) { gkeyboard->pushKeyEvent(true, (unsigned char) event.text.unicode); gkeyboard->pushKeyEvent(false, (unsigned char) event.text.unicode); } // Ignore silenty any other TextEntered events // because SFML generate at same time KeyEvent and TextEntered if (event.type == sf::Event::TextEntered) continue; if (event.key.code>=sf::Keyboard::A && event.key.code<=sf::Keyboard::Z) { if (event.key.shift) keycode=event.key.code+'A'; else keycode=event.key.code+'a'; } else if (event.key.code>=sf::Keyboard::Num0 && event.key.code<=sf::Keyboard::Num9) { keycode=event.key.code-sf::Keyboard::Num0+'0'; } else { switch (event.key.code) { case sf::Keyboard::Space: keycode=' '; break; case sf::Keyboard::BackSpace: keycode=keyboard::BACKSPACE; break; case sf::Keyboard::Return: keycode=keyboard::RETURN; break; case sf::Keyboard::Insert: keycode=keyboard::INSERT; break; case sf::Keyboard::Delete: keycode=keyboard::DELETE; break; case sf::Keyboard::Up: keycode=keyboard::ARROW_UP; break; case sf::Keyboard::Down: keycode=keyboard::ARROW_DOWN; break; case sf::Keyboard::Left: keycode=keyboard::ARROW_LEFT; break; case sf::Keyboard::Right: keycode=keyboard::ARROW_RIGHT; break; case sf::Keyboard::RShift: case sf::Keyboard::LShift: keycode=keyboard::SHIFT; break; case sf::Keyboard::RControl: case sf::Keyboard::LControl: keycode=keyboard::CONTROL; break; case sf::Keyboard::Escape: keycode=keyboard::ESC; break; default: break; } } if (keycode) gkeyboard->pushKeyEvent(pressed,keycode); } } while (window.pollEvent(event)) { // Close window : exit if (event.type == sf::Event::Closed) { window.close(); } else if (event.type == sf::Event::Resized) { //Rewrap opengl camera float r_width = window.getSize().x; float r_height = window.getSize().y; sf::FloatRect r(0,0,r_width,r_height); window.setView(sf::View(r)); } // NOTE This keyboard events should be handled by sf:Keyboard // direclty and only works if any VM window have focus. // Actually only wokrs if the monitor window have focus else if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased) { bool pressed = (event.type == sf::Event::KeyPressed); switch (event.key.code) { case sf::Keyboard::F1: if (debug && pressed) { std::cout << disassembly(dcpu->getMem() +dcpu->GetPC(),3); std::cout << std::endl; dcpu->step(); } break; case sf::Keyboard::F2: if (debug && !pressed) { printf("A : 0x%04X | B : 0x%04X | C : 0x%04X\n", dcpu->ra,dcpu->rb,dcpu->rc); printf("X : 0x%04X | Y : 0x%04X | Z : 0x%04X\n", dcpu->rx,dcpu->ry,dcpu->rz); printf("I : 0x%04X | J : 0x%04X | IA: 0x%04X\n", dcpu->ri,dcpu->rj,dcpu->ria); printf("PC: 0x%04X | SP: 0x%04X | EX: 0x%04X\n", dcpu->rpc,dcpu->rsp,dcpu->rex); } break; case sf::Keyboard::F3: //No need to be in debug mode for this one if (!pressed) { std::cout << "reset dcpu" << std::endl; dcpu->reset(); dcpu->loadProgramFromFile(filename); } break; case sf::Keyboard::F12: if (!pressed) { debug = !debug; } break; default: break; } } } ///DCPU emulation stuff monitor->prepareRender(); const auto delta=clock.getElapsedTime().asMicroseconds(); //.asSeconds(); clock.restart(); if (!debug) { unsigned int tick_needed; if (use_time) tick_needed= delta / 10; else tick_needed=dcpu->cpu_clock/50; // Makes simulation to float around 100% of speed if (compensate_time) tick_needed++; compensate_time ^= 1; // Avoids fill the screen of data if ((dcpu->getTotCycles() % 10000) <= 100) { std::cerr << "Delta: " << delta << " ms "; std::cerr << "Ticks: " << tick_needed << " "; double tmp = tick_needed*(1 / (double)(dcpu->cpu_clock)); int64_t rtime = 1000000 * tmp; std::cerr << "Speed: " << (float)(100*delta)/rtime << std::endl; } dcpu->tick(tick_needed); } window.setActive(true); //Working resizing code border_add = monitor->borderSize(); texture.loadFromImage(*screen); //Slow function sprite.setTexture(texture); sprite.setScale( //Warning setScale and scale are different !! (float)(window.getSize().x-border_add*2)/(float)(monitor->width()), (float)(window.getSize().y-border_add*2)/(float)(monitor->height())); sprite.setPosition(sf::Vector2f(border_add,border_add)); window.clear(monitor->getBorder()); //good idea window.draw(sprite); window.display(); window.setActive(false); // Updates Keyboard window if (keyb_image_loaded) { keyb_win.setActive(true); keyb_win.clear(); keyb_win.draw(keyb_sprite); keyb_win.display(); keyb_win.setActive(false); } } gen.stop(); return 0; } <commit_msg>Tweaked delta time calculation to be a bit more precise. Plus Delta time & speed info now are showed in a reliable way every second<commit_after>#include <iostream> #include <cstdint> #include <algorithm> #include <memory> #include <stdio.h> #include <chrono> #include <cmath> #include "config.hpp" // Machine core #include <dcpu_opcodes.hpp> #include <dcpu.hpp> // Devices #include <devices/gclock.hpp> #include <devices/gkeyboard.hpp> #include <devices/lem1802.hpp> #include <devices/lem1803.hpp> #include <devices/cgm.hpp> #include <devices/speaker.hpp> // Audio #include <audio/square_gen.hpp> // Util #include <disassembler.hpp> #include <binasm.hpp> using namespace cpu; void print_help(std::string program_name) { std::cout << "usage : " << program_name << " [-options] <dcpu16-exe>\n"; std::cout << "--------------------------------------------------------\n"; std::cout << " options:" << std::endl; std::cout << " -assemble (-a) : assemble before load (experimental)\n"; std::cout << " -debug (-d) : start in debug mode\n"; std::cout << " F1 : next step" << std::endl; std::cout << " F2 : print registers" << std::endl; std::cout << " F3 : reset (no need debug mode)" << std::endl; std::cout << " F12 : switch debug/run" << std::endl; std::cout << " --monitor=<monitor_name> : use the following monitor\n"; std::cout << " 1802 -> Lem1802 (default) [c] (-1802)\n"; std::cout << " 1803 -> Lem1803 [c] (-1803)" << std::endl; std::cout << " cgm -> Colour Graphics Monitor (-cgm)\n"; std::cout << " [c] : compatible with Lem1802 0x10c programs\n"; std::cout << " -output <filename> (-o) : output assembled filename\n"; std::cout << " -time (-t) : use timed emulation (else refresh based)\n"; std::cout << " -vsync (-v) : use vertical synchronisation\n"; std::cout << " (more accurate but may bug)\n"; } int main (int argc, char **argv) { std::string filename; std::string outname="a.out"; //output assembled filename int monitor_type=0; bool debug=false; //use vsync for refresh the screen (more accuracte than setFrameLimit) bool use_vsync=false; //use time emulation based on sf::Clock; bool use_time=false; //need asssemble the file bool assemble=false; //TODO make a fonction that parse argument into a program struct for (int k=1; k < argc; k++) //parse arguments { if (argv[k][0] == '-') { std::string opt = argv[k]; if (opt=="--help"||opt=="-help"||opt=="-h") { std::string pn = argv[0]; pn.erase(0,pn.find_last_of('\\')+1); //windows pn.erase(0,pn.find_last_of('/')+1); //linux print_help(pn); return 0; } else if (opt=="-debug") debug=true; else if (opt=="-1802"||opt=="--monitor=1802") monitor_type=0; else if (opt=="-1803"||opt=="--monitor=1803") monitor_type=1; else if (opt=="-cgm"||opt=="--monitor=cgm") monitor_type=2; else if (opt.find("--monitor") != std::string::npos) { std::cout << "warning: unknow monitor type "; std::cout << opt << std::endl; } else if (opt == "-vsync" || opt == "-v") use_vsync=true; else if (opt == "-time" || opt == "-t") use_time=true; else if (opt == "-assemble" || opt == "-a") assemble=true; else if ((opt == "-output" || opt == "-o") && argc > k+1) { assemble=true; outname = argv[k+1]; k++; } else if (opt == "-output" || opt == "-o") { std::cout << "warning: option " << opt << " requiert"; std::cout << " another argument it will be ignored here"; } else { std::cout << "warning: unknow option "; std::cout << opt << " it will be ignored !" << std::endl; } } else { filename = argv[k]; } } if (assemble) { BinAsm assembler; if (!assembler.load(filename)) return 0xdead; if (!assembler.assemble()) return 0xdead; if (!assembler.resolve_labels()) return 0xdead; if (!assembler.save(outname)) return 0xdead; filename = outname; } if (argc <= 1 || !filename.size()) { std::cerr <<"error: missing input file, type --help for list options\n"; return 0; } sf::String window_title="dcpu_vm"; auto dcpu = std::make_shared<DCPU>(); auto gclock = std::make_shared<Generic_Clock>(); auto gkeyboard = std::make_shared<keyboard::GKeyboard>(); // Prepare the speaker device auto speaker = std::make_shared<speaker::Speaker>(); audio::SquareGenerator gen; gen.prepare(44100); gen.play(); speaker->setFreqCallback(audio::SquareGenerator::WrappeCallback, (void *)(&gen)); // Sets apropiated monitor std::shared_ptr<AbstractMonitor> monitor; switch (monitor_type) { case 1: monitor=std::make_shared<lem::Lem1803>(); std::cout << "use Lem1803 Monitor" << std::endl; window_title = "Lem 1803"; break; case 2: monitor=std::make_shared<cgm::CGM>(); std::cout << "use CGM Monitor" << std::endl; window_title = "CGM"; break; default : monitor=std::make_shared<lem::Lem1802>(); std::cout << "use Lem1802 Monitor" << std::endl; window_title = "Lem 1802"; break; } dcpu->attachHardware (monitor); dcpu->attachHardware (gclock); dcpu->attachHardware (gkeyboard); dcpu->attachHardware (speaker); dcpu->reset(); dcpu->loadProgramFromFile(filename); sf::Texture texture; // texture of the screen sf::Sprite sprite; //sprite of the screen const sf::Image* screen = monitor->getScreen(); sf::Clock clock; sf::RenderWindow window; float border_add = monitor->borderSize()*2; window.create(sf::VideoMode(monitor->phyWidth()+border_add, monitor->phyHeight()+border_add), window_title); if (use_vsync) { std::cout << "warning: vsync activated may bug" << std::endl; window.setVerticalSyncEnabled(true); } else window.setFramerateLimit(50); // We try to use a window to show a fake keyboard and capture keyboard // events if it have focus sf::RenderWindow keyb_win; keyb_win.create(sf::VideoMode(484, 196), "Keyboard", sf::Style::Titlebar | sf::Style::Close); keyb_win.setKeyRepeatEnabled(false); keyb_win.setActive(false); sf::Texture keyb_tx; bool keyb_image_loaded = keyb_tx.loadFromFile("assets/keyb_img.png"); sf::Sprite keyb_sprite; if (keyb_image_loaded) keyb_sprite.setTexture(keyb_tx); else std::cerr << "Waring: assets/keyb_img.png not found !" << std::endl; bool keyb_focus; unsigned long ticks_counter = 0; while (window.isOpen() && keyb_win.isOpen()) { //Because non mainthread event are forbidden in OSX // Process events sf::Event event; while (keyb_win.pollEvent(event)) { // This window capture key events to the VM window if have focus if (event.type == sf::Event::Closed) { keyb_win.close(); } else if (event.type == sf::Event::GainedFocus) { keyb_focus = true; } else if (event.type == sf::Event::LostFocus) { keyb_focus = false; } else if (keyb_focus && ( event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased || event.type == sf::Event::TextEntered )) { // Process VM keyboard input bool pressed = (event.type == sf::Event::KeyPressed); unsigned char keycode=0; // Note this works becuase Unicode maps ASCII 7 bit in his // first 128 codes if (event.type == sf::Event::TextEntered && ((event.text.unicode >= '!' && event.text.unicode <= '/') || (event.text.unicode >= ':' && event.text.unicode <= '@') || (event.text.unicode >= '[' && event.text.unicode <= 0x60) || (event.text.unicode >= '{' && event.text.unicode <= 0x7F) )) { gkeyboard->pushKeyEvent(true, (unsigned char) event.text.unicode); gkeyboard->pushKeyEvent(false, (unsigned char) event.text.unicode); } // Ignore silenty any other TextEntered events // because SFML generate at same time KeyEvent and TextEntered if (event.type == sf::Event::TextEntered) continue; if (event.key.code>=sf::Keyboard::A && event.key.code<=sf::Keyboard::Z) { if (event.key.shift) keycode=event.key.code+'A'; else keycode=event.key.code+'a'; } else if (event.key.code>=sf::Keyboard::Num0 && event.key.code<=sf::Keyboard::Num9) { keycode=event.key.code-sf::Keyboard::Num0+'0'; } else { switch (event.key.code) { case sf::Keyboard::Space: keycode=' '; break; case sf::Keyboard::BackSpace: keycode=keyboard::BACKSPACE; break; case sf::Keyboard::Return: keycode=keyboard::RETURN; break; case sf::Keyboard::Insert: keycode=keyboard::INSERT; break; case sf::Keyboard::Delete: keycode=keyboard::DELETE; break; case sf::Keyboard::Up: keycode=keyboard::ARROW_UP; break; case sf::Keyboard::Down: keycode=keyboard::ARROW_DOWN; break; case sf::Keyboard::Left: keycode=keyboard::ARROW_LEFT; break; case sf::Keyboard::Right: keycode=keyboard::ARROW_RIGHT; break; case sf::Keyboard::RShift: case sf::Keyboard::LShift: keycode=keyboard::SHIFT; break; case sf::Keyboard::RControl: case sf::Keyboard::LControl: keycode=keyboard::CONTROL; break; case sf::Keyboard::Escape: keycode=keyboard::ESC; break; default: break; } } if (keycode) gkeyboard->pushKeyEvent(pressed,keycode); } } while (window.pollEvent(event)) { // Close window : exit if (event.type == sf::Event::Closed) { window.close(); } else if (event.type == sf::Event::Resized) { //Rewrap opengl camera float r_width = window.getSize().x; float r_height = window.getSize().y; sf::FloatRect r(0,0,r_width,r_height); window.setView(sf::View(r)); } // NOTE This keyboard events should be handled by sf:Keyboard // direclty and only works if any VM window have focus. // Actually only wokrs if the monitor window have focus else if (event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased) { bool pressed = (event.type == sf::Event::KeyPressed); switch (event.key.code) { case sf::Keyboard::F1: if (debug && pressed) { std::cout << disassembly(dcpu->getMem() +dcpu->GetPC(),3); std::cout << std::endl; dcpu->step(); } break; case sf::Keyboard::F2: if (debug && !pressed) { printf("A : 0x%04X | B : 0x%04X | C : 0x%04X\n", dcpu->ra,dcpu->rb,dcpu->rc); printf("X : 0x%04X | Y : 0x%04X | Z : 0x%04X\n", dcpu->rx,dcpu->ry,dcpu->rz); printf("I : 0x%04X | J : 0x%04X | IA: 0x%04X\n", dcpu->ri,dcpu->rj,dcpu->ria); printf("PC: 0x%04X | SP: 0x%04X | EX: 0x%04X\n", dcpu->rpc,dcpu->rsp,dcpu->rex); } break; case sf::Keyboard::F3: //No need to be in debug mode for this one if (!pressed) { std::cout << "reset dcpu" << std::endl; dcpu->reset(); dcpu->loadProgramFromFile(filename); } break; case sf::Keyboard::F12: if (!pressed) { debug = !debug; } break; default: break; } } } ///DCPU emulation stuff monitor->prepareRender(); // T period of a 100KHz signal = 10 microseconds const auto delta=clock.getElapsedTime().asMicroseconds(); clock.restart(); if (!debug) { unsigned int tick_needed; if (use_time) { double tmp = delta / 10.0f; tick_needed= std::round(tmp); } else { double tmp = dcpu->cpu_clock/50; tick_needed= std::round(tmp); } ticks_counter += tick_needed; // Outputs every second (if runs to ~100% of speed) if (ticks_counter > 100000) { ticks_counter -= 100000; std::cerr << "Delta: " << delta << " ms "; std::cerr << "Ticks: " << tick_needed << " "; double tmp = tick_needed*(1 / (double)(dcpu->cpu_clock)); int64_t rtime = 1000000 * tmp; std::cerr << "Speed: " << (float)(100*delta)/rtime << std::endl; } dcpu->tick(tick_needed); } window.setActive(true); //Working resizing code border_add = monitor->borderSize(); texture.loadFromImage(*screen); //Slow function sprite.setTexture(texture); sprite.setScale( //Warning setScale and scale are different !! (float)(window.getSize().x-border_add*2)/(float)(monitor->width()), (float)(window.getSize().y-border_add*2)/(float)(monitor->height())); sprite.setPosition(sf::Vector2f(border_add,border_add)); window.clear(monitor->getBorder()); //good idea window.draw(sprite); window.display(); window.setActive(false); // Updates Keyboard window if (keyb_image_loaded) { keyb_win.setActive(true); keyb_win.clear(); keyb_win.draw(keyb_sprite); keyb_win.display(); keyb_win.setActive(false); } } gen.stop(); return 0; } <|endoftext|>
<commit_before>#include <algorithm> #include <chrono> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> #include <vector> #include "init.h" #include "util.h" #include "version.h" using std::chrono::duration; using std::chrono::steady_clock; using std::cin; using std::cout; using std::endl; using std::ifstream; using std::map; using std::setprecision; using std::size_t; using std::stoul; using std::string; using std::stringstream; using std::to_string; using std::unique_ptr; using std::vector; void DoProcessing(vector<string> *i, const unique_ptr<map<string, vector<string>>> &m_token, const unique_ptr<map<string, vector<string>>> &v_token, const unique_ptr<vector<vector<string>>> &patterns) { for (size_t it = 0; it < i->size(); ++it) { // input vector size checks if (i->size() <= 1) { break; } // punctuation checks if (i->at(it).back() == ',') { // (.+), i->at(it).pop_back(); continue; } else if ((i->at(it).back()) == '.' && (i->at(it).at(i->at(it).size() - 2)) != '.') { // (.+)(?!(\.+)\.) i->at(it).pop_back(); continue; } else if (i->at(it).find("\'") != string::npos) { // (.*\'.*) i.e. contractions MergeTokens(i, it); continue; } // string length checks if (CheckStringLength(i->at(it), 6)) { // don't process if word is longer than 6-char continue; } // word pattern matches vector<string> *match = nullptr; string modifier{}; for (auto &&p : *patterns) { // loop patterns if (match != nullptr) { break; } match = &p; for (size_t iit = 0; iit < p.size(); ++iit) { // loop pattern tokens modifier = ""; string pattern{ReadTokenType(p.at(iit))}; if (pattern.at(0) == 'T') { if (StringIsMatch(i->at(it + iit), m_token->at(pattern.substr(1, pattern.size())))) { continue; } } else if (pattern.at(0) == 'L') { if (StringIsMatch(i->at(it + iit), {pattern.substr(1, pattern.size())})) { continue; } } else if (pattern.at(0) == 'W') { continue; } else if (pattern.at(0) == 'V') { if (pattern.at(1) == 'W') { if (SearchVerbTokens(i->at(it + iit), v_token)) { continue; } } else { if (SearchVerbTokens(i->at(it + iit), v_token, pattern.substr(1, pattern.size()))) { continue; } } } else if ((pattern.at(0) == 'M') && (pattern.find("VERSION") == string::npos)) { modifier = pattern.substr(1, pattern.size()); continue; } match = nullptr; break; } } if (match != nullptr) { for (size_t l = 1; l < match->size(); ++l) if (modifier != "") { ++l; if (modifier.substr(0, 2) == "l=") { MergeTokens(i, it, stoul(modifier.substr(2, modifier.size()))); } else { MergeTokens(i, it); } } else { MergeTokens(i, it); } } } } void OutputHelp(const char c[]) { cout << "Usage: " << c << " [OPTION]..." << endl; cout << "Converts a sentence to line-delimited phrases" << endl << endl; cout << " -t, --token=[FILE]\tset token file path to [FILE]" << endl; cout << " -p, --pattern=[FILE]\tset pattern file path to [FILE]" << endl; cout << " --help\t\tdisplay this help and exit" << endl; cout << " --version\t\toutput version information and exit" << endl; } int main(int argc, char *argv[]) { // read input arguments vector<string> argvec{}; if (argc > 1) { for (int i = 1; i < argc; i++) { argvec.emplace_back(argv[i]); } } // analyze command line switches string token_src = "../tokens"; string pattern_src = "../patterns"; for (size_t i = 0; i < argvec.size(); ++i) { if (argvec.at(i) == "-t") { token_src = argvec.at(++i); } else if (argvec.at(i) == "-p") { pattern_src = argvec.at(++i); } else if (argvec.at(i).substr(0, 6) == "--token=") { token_src = argvec.at(i).substr(6, argvec.at(i).size()); } else if (argvec.at(i).substr(0, 10) == "--pattern=") { pattern_src = argvec.at(++i); } else if (argvec.at(i) == "--help") { OutputHelp(argv[0]); return 0; } else if (argvec.at(i) == "--version") { cout << "Amyspeak " << kBuildString << endl; cout << "Copyright (C) 2017 Derppening" << endl; cout << "Written by David Mak." << endl; return 0; } } if (token_src.at(0) != '.' && token_src.at(1) != '.') { token_src.insert(0, "./"); } if (pattern_src.at(0) != '.' && pattern_src.at(1) != '.') { pattern_src.insert(0, "./"); } cout << "Reading tokens from " << token_src << endl; cout << "Reading patterns from " << pattern_src << endl; // see if the files exist unique_ptr<ifstream> token_file(new ifstream(token_src)); if (!token_file->is_open()) { cout << "Error: Tokens file not found. Exiting." << endl; return 0; } unique_ptr<ifstream> pattern_file(new ifstream(pattern_src)); if (!pattern_file->is_open()) { cout << "Error: Patterns file not found. Exiting." << endl; return 0; } auto time = steady_clock::now(); // read and save normal tokens cout << "Initializing tokens... "; auto tokens = ParseTokens(*token_file); auto token_pos = ParseTokenCategories(*tokens); auto match_tokens = ConstructMatchingTokens(*tokens, *token_pos); cout << "Done." << endl; // read and save verb tokens cout << "Initializing verb tokens... "; unique_ptr<map<string, vector<string>>> match_verbs = nullptr; for (auto &&i : *token_pos) { if (i.second == "verb") { match_verbs = ConstructVerbToken(*tokens, i.first); break; } } if (match_verbs == nullptr) { cout << "Not found." << endl; } else { cout << "Done." << endl; } const string token_version_string = ReadTokensVersion(*tokens); tokens.reset(nullptr); token_file.reset(nullptr); token_pos.reset(nullptr); // read and save patterns cout << "Initializing patterns... "; auto patterns = ParsePatterns(*pattern_file, match_tokens, match_verbs); const string pattern_version_string = ReadPatternsVersion(*patterns); cout << "Done." << endl; pattern_file.reset(nullptr); if (token_version_string != "") { cout << "Tokens library version: " << token_version_string << endl; } if (pattern_version_string != "") { cout << "Patterns library version: " << pattern_version_string << endl; } auto time_taken = duration<double, std::milli>(steady_clock::now() - time); cout << setprecision(4) << "Initialization complete. Took " << time_taken.count() << " ms." << endl << endl; cout << "Type ':clear' to clear the console, "<< endl << " ':q' to quit." << endl; while (true) { cout << "> "; string input; getline(cin, input); if (input == ":q") break; string buf{}; stringstream ss_buf(input); vector<string> input_tokens; while (ss_buf >> buf) { input_tokens.emplace_back(buf); } // do processing if (input_tokens.size() == 1) { if (input_tokens.at(0) == "exit") { cout << "Type ':q' to quit" << endl; continue; } else if (input_tokens.at(0) == ":clear") { if (system("cls")) { system("clear"); } continue; } } DoProcessing(&input_tokens, match_tokens, match_verbs, patterns); OutputTokens(input_tokens); } return 0; } <commit_msg>Separate Version Info to a new function<commit_after>#include <algorithm> #include <chrono> #include <fstream> #include <iomanip> #include <iostream> #include <map> #include <memory> #include <sstream> #include <string> #include <vector> #include "init.h" #include "util.h" #include "version.h" using std::chrono::duration; using std::chrono::steady_clock; using std::cin; using std::cout; using std::endl; using std::ifstream; using std::map; using std::setprecision; using std::size_t; using std::stoul; using std::string; using std::stringstream; using std::to_string; using std::unique_ptr; using std::vector; void DoProcessing(vector<string> *i, const unique_ptr<map<string, vector<string>>> &m_token, const unique_ptr<map<string, vector<string>>> &v_token, const unique_ptr<vector<vector<string>>> &patterns) { for (size_t it = 0; it < i->size(); ++it) { // input vector size checks if (i->size() <= 1) { break; } // punctuation checks if (i->at(it).back() == ',') { // (.+), i->at(it).pop_back(); continue; } else if ((i->at(it).back()) == '.' && (i->at(it).at(i->at(it).size() - 2)) != '.') { // (.+)(?!(\.+)\.) i->at(it).pop_back(); continue; } else if (i->at(it).find("\'") != string::npos) { // (.*\'.*) i.e. contractions MergeTokens(i, it); continue; } // string length checks if (CheckStringLength(i->at(it), 6)) { // don't process if word is longer than 6-char continue; } // word pattern matches vector<string> *match = nullptr; string modifier{}; for (auto &&p : *patterns) { // loop patterns if (match != nullptr) { break; } match = &p; for (size_t iit = 0; iit < p.size(); ++iit) { // loop pattern tokens modifier = ""; string pattern{ReadTokenType(p.at(iit))}; if (pattern.at(0) == 'T') { if (StringIsMatch(i->at(it + iit), m_token->at(pattern.substr(1, pattern.size())))) { continue; } } else if (pattern.at(0) == 'L') { if (StringIsMatch(i->at(it + iit), {pattern.substr(1, pattern.size())})) { continue; } } else if (pattern.at(0) == 'W') { continue; } else if (pattern.at(0) == 'V') { if (pattern.at(1) == 'W') { if (SearchVerbTokens(i->at(it + iit), v_token)) { continue; } } else { if (SearchVerbTokens(i->at(it + iit), v_token, pattern.substr(1, pattern.size()))) { continue; } } } else if ((pattern.at(0) == 'M') && (pattern.find("VERSION") == string::npos)) { modifier = pattern.substr(1, pattern.size()); continue; } match = nullptr; break; } } if (match != nullptr) { for (size_t l = 1; l < match->size(); ++l) if (modifier != "") { ++l; if (modifier.substr(0, 2) == "l=") { MergeTokens(i, it, stoul(modifier.substr(2, modifier.size()))); } else { MergeTokens(i, it); } } else { MergeTokens(i, it); } } } } void OutputHelp(const char c[]) { cout << "Usage: " << c << " [OPTION]..." << endl; cout << "Converts a sentence to line-delimited phrases" << endl << endl; cout << " -t, --token=[FILE]\tset token file path to [FILE]" << endl; cout << " -p, --pattern=[FILE]\tset pattern file path to [FILE]" << endl; cout << " --help\t\tdisplay this help and exit" << endl; cout << " --version\t\toutput version information and exit" << endl; } void OutputVersionInfo() { cout << "Amyspeak " << kBuildString << endl; cout << "Copyright (C) 2017 Derppening" << endl; cout << "Written by David Mak." << endl; } int main(int argc, char *argv[]) { // read input arguments vector<string> argvec{}; if (argc > 1) { for (int i = 1; i < argc; i++) { argvec.emplace_back(argv[i]); } } // analyze command line switches string token_src = "../tokens"; string pattern_src = "../patterns"; for (size_t i = 0; i < argvec.size(); ++i) { if (argvec.at(i) == "-t") { token_src = argvec.at(++i); } else if (argvec.at(i) == "-p") { pattern_src = argvec.at(++i); } else if (argvec.at(i).substr(0, 6) == "--token=") { token_src = argvec.at(i).substr(6, argvec.at(i).size()); } else if (argvec.at(i).substr(0, 10) == "--pattern=") { pattern_src = argvec.at(++i); } else if (argvec.at(i) == "--help") { OutputHelp(argv[0]); return 0; } else if (argvec.at(i) == "--version") { OutputVersionInfo(); return 0; } } if (token_src.at(0) != '.' && token_src.at(1) != '.') { token_src.insert(0, "./"); } if (pattern_src.at(0) != '.' && pattern_src.at(1) != '.') { pattern_src.insert(0, "./"); } cout << "Reading tokens from " << token_src << endl; cout << "Reading patterns from " << pattern_src << endl; // see if the files exist unique_ptr<ifstream> token_file(new ifstream(token_src)); if (!token_file->is_open()) { cout << "Error: Tokens file not found. Exiting." << endl; return 0; } unique_ptr<ifstream> pattern_file(new ifstream(pattern_src)); if (!pattern_file->is_open()) { cout << "Error: Patterns file not found. Exiting." << endl; return 0; } auto time = steady_clock::now(); // read and save normal tokens cout << "Initializing tokens... "; auto tokens = ParseTokens(*token_file); auto token_pos = ParseTokenCategories(*tokens); auto match_tokens = ConstructMatchingTokens(*tokens, *token_pos); cout << "Done." << endl; // read and save verb tokens cout << "Initializing verb tokens... "; unique_ptr<map<string, vector<string>>> match_verbs = nullptr; for (auto &&i : *token_pos) { if (i.second == "verb") { match_verbs = ConstructVerbToken(*tokens, i.first); break; } } if (match_verbs == nullptr) { cout << "Not found." << endl; } else { cout << "Done." << endl; } const string token_version_string = ReadTokensVersion(*tokens); tokens.reset(nullptr); token_file.reset(nullptr); token_pos.reset(nullptr); // read and save patterns cout << "Initializing patterns... "; auto patterns = ParsePatterns(*pattern_file, match_tokens, match_verbs); const string pattern_version_string = ReadPatternsVersion(*patterns); cout << "Done." << endl; pattern_file.reset(nullptr); if (token_version_string != "") { cout << "Tokens library version: " << token_version_string << endl; } if (pattern_version_string != "") { cout << "Patterns library version: " << pattern_version_string << endl; } auto time_taken = duration<double, std::milli>(steady_clock::now() - time); cout << setprecision(4) << "Initialization complete. Took " << time_taken.count() << " ms." << endl << endl; cout << "Type ':clear' to clear the console, "<< endl << " ':q' to quit." << endl; while (true) { cout << "> "; string input; getline(cin, input); if (input == ":q") break; string buf{}; stringstream ss_buf(input); vector<string> input_tokens; while (ss_buf >> buf) { input_tokens.emplace_back(buf); } // do processing if (input_tokens.size() == 1) { if (input_tokens.at(0) == "exit") { cout << "Type ':q' to quit" << endl; continue; } else if (input_tokens.at(0) == ":clear") { if (system("cls")) { system("clear"); } continue; } } DoProcessing(&input_tokens, match_tokens, match_verbs, patterns); OutputTokens(input_tokens); } return 0; } <|endoftext|>
<commit_before>#include <QLabel> #include <QSurfaceFormat> #include <QCommandLineParser> #include <iostream> #include <stdio.h> #include <QMainWindow> #include <QDir> #include "scene/imagereader.h" #include "application.h" #ifndef QT_NO_OPENGL #include "projector.h" #endif struct ProjectorOptions { QString imageplane; QString template_path; QString project_path; QStringList scene_files; }; enum CommandLineParseResult { CommandLineOk, CommandLineError, CommandLineVersionRequested, CommandLineHelpRequested, }; CommandLineParseResult parseCommandLine(QCommandLineParser &parser, ProjectorOptions &options, QString &errorMessage) { parser.setApplicationDescription(QCoreApplication::translate( "Projector", "Projection template tool.")); parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions); const QCommandLineOption imageplane_option(QStringList() << "i" << "imageplane", "use <image seqence> as imageplane.", "image sequence"); parser.addOption(imageplane_option); const QCommandLineOption project_option(QStringList() << "p" << "project", "project directory, were to output images too.", "project directory"); parser.addOption(project_option); QCommandLineOption template_option(QStringList() << "t" << "template", "template texture.", "template.png"); template_option.setDefaultValue(":/textures/dog_guides.png"); parser.addOption(template_option); const QCommandLineOption helpOption = parser.addHelpOption(); const QCommandLineOption versionOption = parser.addVersionOption(); parser.addPositionalArgument("files", "Files to open", "[files ...]"); if (!parser.parse(QCoreApplication::arguments())) { errorMessage = parser.errorText(); return CommandLineError; } if (parser.isSet(versionOption)) return CommandLineVersionRequested; if (parser.isSet(helpOption)) return CommandLineHelpRequested; options.imageplane = parser.value(imageplane_option); options.project_path = parser.value(project_option); options.template_path = parser.value(template_option); options.scene_files = parser.positionalArguments(); return CommandLineOk; } int main(int argc, char *argv[]) { Application app(argc, argv); app.setApplicationName("glprojectiontool"); app.setApplicationVersion("0.1"); app.setWindowIcon(QIcon(":/textures/icon.png")); qRegisterMetaType<std::vector < float > > ("FloatImage"); qRegisterMetaType<FloatImageData>("FloatImageData"); QSurfaceFormat format; format.setVersion(3, 3); format.setProfile(QSurfaceFormat::CoreProfile); format.setDepthBufferSize(24); format.setStencilBufferSize(8); format.setSamples(8); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); QSurfaceFormat::setDefaultFormat(format); QCommandLineParser parser; QString errorMessage; ProjectorOptions options; switch (parseCommandLine(parser, options, errorMessage)) { case CommandLineOk: break; case CommandLineError: fputs(qPrintable(errorMessage), stderr); fputs("\n\n", stderr); fputs(qPrintable(parser.helpText()), stderr); return 1; case CommandLineVersionRequested: printf("%s %s\n", qPrintable(QCoreApplication::applicationName()), qPrintable(QCoreApplication::applicationVersion())); return 0; case CommandLineHelpRequested: parser.showHelp(); return 0; } Projector widget; //widget.setAttribute(Qt::WA_NoSystemBackground); //widget.setAttribute(Qt::WA_OpaquePaintEvent); //widget.setAttribute(Qt::WA_NativeWindow); //widget.setAttribute(Qt::WA_PaintOnScreen); QObject::connect(&app, SIGNAL(file_open_event(QUrl)), &widget, SLOT(file_open_event(QUrl))); std::cerr << "imageplane " << options.imageplane.toStdString() << "\n"; widget.set_imageplane(options.imageplane); if (!options.template_path.isEmpty()) widget.set_template_texture(options.template_path); for (int i = 0; i < options.scene_files.size(); i++) { std::cerr << "opening " << options.scene_files[i].toStdString() << "\n"; widget.open(options.scene_files[i]); } QString project_path = options.project_path; if (project_path.isEmpty()) project_path = QDir::currentPath(); std::cerr << "project " << project_path.toStdString() << "\n"; widget.set_project(project_path); widget.resize(QSize(1200,600)); widget.show(); //QMainWindow window; //window.setCentralWidget(&widget); //window.show(); return app.exec(); } <commit_msg>take glpt as a arg<commit_after>#include <QLabel> #include <QSurfaceFormat> #include <QCommandLineParser> #include <iostream> #include <stdio.h> #include <QMainWindow> #include <QDir> #include "scene/imagereader.h" #include "application.h" #ifndef QT_NO_OPENGL #include "projector.h" #endif struct ProjectorOptions { QString imageplane; QString template_path; QString project_path; QStringList scene_files; }; enum CommandLineParseResult { CommandLineOk, CommandLineError, CommandLineVersionRequested, CommandLineHelpRequested, }; CommandLineParseResult parseCommandLine(QCommandLineParser &parser, ProjectorOptions &options, QString &errorMessage) { parser.setApplicationDescription(QCoreApplication::translate( "Projector", "Projection template tool.")); parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions); const QCommandLineOption imageplane_option(QStringList() << "i" << "imageplane", "use <image seqence> as imageplane.", "image sequence"); parser.addOption(imageplane_option); const QCommandLineOption project_option(QStringList() << "p" << "project", "project directory, were to output images too.", "project directory"); parser.addOption(project_option); QCommandLineOption template_option(QStringList() << "t" << "template", "template texture.", "template.png"); template_option.setDefaultValue(":/textures/dog_guides.png"); parser.addOption(template_option); const QCommandLineOption helpOption = parser.addHelpOption(); const QCommandLineOption versionOption = parser.addVersionOption(); parser.addPositionalArgument("files", "Files to open", "[files ...]"); if (!parser.parse(QCoreApplication::arguments())) { errorMessage = parser.errorText(); return CommandLineError; } if (parser.isSet(versionOption)) return CommandLineVersionRequested; if (parser.isSet(helpOption)) return CommandLineHelpRequested; options.imageplane = parser.value(imageplane_option); options.project_path = parser.value(project_option); options.template_path = parser.value(template_option); options.scene_files = parser.positionalArguments(); return CommandLineOk; } int main(int argc, char *argv[]) { Application app(argc, argv); app.setApplicationName("glprojectiontool"); app.setApplicationVersion("0.1"); app.setWindowIcon(QIcon(":/textures/icon.png")); qRegisterMetaType<std::vector < float > > ("FloatImage"); qRegisterMetaType<FloatImageData>("FloatImageData"); QSurfaceFormat format; format.setVersion(3, 3); format.setProfile(QSurfaceFormat::CoreProfile); format.setDepthBufferSize(24); format.setStencilBufferSize(8); format.setSamples(8); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); QSurfaceFormat::setDefaultFormat(format); QCommandLineParser parser; QString errorMessage; ProjectorOptions options; switch (parseCommandLine(parser, options, errorMessage)) { case CommandLineOk: break; case CommandLineError: fputs(qPrintable(errorMessage), stderr); fputs("\n\n", stderr); fputs(qPrintable(parser.helpText()), stderr); return 1; case CommandLineVersionRequested: printf("%s %s\n", qPrintable(QCoreApplication::applicationName()), qPrintable(QCoreApplication::applicationVersion())); return 0; case CommandLineHelpRequested: parser.showHelp(); return 0; } Projector widget; //widget.setAttribute(Qt::WA_NoSystemBackground); //widget.setAttribute(Qt::WA_OpaquePaintEvent); //widget.setAttribute(Qt::WA_NativeWindow); //widget.setAttribute(Qt::WA_PaintOnScreen); QObject::connect(&app, SIGNAL(file_open_event(QUrl)), &widget, SLOT(file_open_event(QUrl))); std::cerr << "imageplane " << options.imageplane.toStdString() << "\n"; widget.set_imageplane(options.imageplane); if (!options.template_path.isEmpty()) widget.set_template_texture(options.template_path); for (int i = 0; i < options.scene_files.size(); i++) { std::cerr << "opening " << options.scene_files[i].toStdString() << "\n"; widget.file_open_event(QUrl::fromLocalFile(options.scene_files[i])); } QString project_path = options.project_path; if (project_path.isEmpty()) project_path = QDir::currentPath(); std::cerr << "project " << project_path.toStdString() << "\n"; widget.set_project(project_path); widget.resize(QSize(1200,600)); widget.show(); //QMainWindow window; //window.setCentralWidget(&widget); //window.show(); return app.exec(); } <|endoftext|>
<commit_before>/* * Blablub * * main.cpp */ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <zmq.hpp> #include <iostream> #include <fstream> #include <cstring> #include <sstream> #include <boost/thread.hpp> #include <signal.h> #include <sys/inotify.h> #include <poll.h> #include "constants.hpp" #include "boxoffice.hpp" #include "publisher.hpp" static int s_interrupted = 0; static void s_signal_handler (int signal_value) { s_interrupted = 1; } static void s_catch_signals () { #if (!defined(WIN32)) struct sigaction action; action.sa_handler = s_signal_handler; action.sa_flags = 0; sigemptyset (&action.sa_mask); sigaction (SIGINT, &action, NULL); sigaction (SIGTERM, &action, NULL); #endif } void *boxoffice_thread(void *arg) //void *boxoffice_thread(void *arg, void *ctx_) { Boxoffice* bo; bo = Boxoffice::initialize(static_cast<zmq::context_t*>(arg)); /* zmq::context_t* z_context(static_cast<zmq::context_t*>(ctx_)); int* fd = static_cast<int*>(arg); zmq::socket_t test(*z_context, ZMQ_SUB); test.connect("inproc://sb_broadcast"); const char *sub_filter = ""; test.setsockopt(ZMQ_SUBSCRIBE, sub_filter, 0); std::cout << "receiving msg" << std::endl; std::stringstream* sstream = new std::stringstream(); s_recv_in(test, *fd, *sstream); std::cout << sstream->str() << std::endl; delete sstream; test.close(); */ /* pollfd pollfd = {*fd, POLLIN, 0}; poll(&pollfd, 1, -1); std::cout << "blub" << std::endl; length = read( *fd, buffer, SB_IN_BUF_LEN ); if ( length < 0 ) perror("inotify poll"); std::cout << "blub" << std::endl; struct inotify_event* event; event = (struct inotify_event*) &buffer[0]; std::cout << event->mask << std::endl; */ return (NULL); } int main(int argc, char* argv[]) { // FORKING /* pid_t pid, sid; // fork off the SUB process pid = fork(); // if pid < 0 the forking failed if (pid < 0) { exit(EXIT_FAILURE); } // pid==0 is the SUB process itself else if (pid == 0) { umask(0); sid = setsid(); if (sid < 0) { exit(EXIT_FAILURE); } */ // opening zeromq context zmq::context_t z_context(1); // we eagerly initialize the Boxoffice- and Publisher-singleton here, // for thread-safety Boxoffice::getInstance(); Publisher::getInstance(); // catch signals s_catch_signals(); /* // bind process broadcast pub zmq::socket_t test(z_context, ZMQ_PUB); test.bind("inproc://sb_broadcast"); int length, i = 0; int fd; int wd; char buffer[SB_IN_BUF_LEN]; fd = inotify_init(); if ( fd < 0 ) perror("inotify_init"); wd = inotify_add_watch( fd, "/home/alex/bin/syncbox/test/testdir2", SB_IN_EVENT_MASK ); if (SB_MSG_DEBUG) printf("main: opening boxoffice thread\n"); boost::thread bo_thread(boxoffice_thread, &fd, &z_context); */ /* std::cout << IN_ACCESS << std::endl; std::cout << IN_ATTRIB << std::endl; std::cout << IN_CLOSE_WRITE << std::endl; std::cout << IN_CLOSE_NOWRITE << std::endl; std::cout << IN_CREATE << std::endl; std::cout << IN_DELETE << std::endl; std::cout << IN_DELETE_SELF << std::endl; std::cout << IN_MODIFY << std::endl; std::cout << IN_MOVE_SELF << std::endl; std::cout << IN_MOVED_FROM << std::endl; std::cout << IN_MOVED_TO << std::endl; std::cout << IN_OPEN << std::endl; std::cout << IN_MOVE << std::endl; std::cout << IN_CLOSE << std::endl; std::cout << IN_DONT_FOLLOW << std::endl; std::cout << IN_EXCL_UNLINK << std::endl; std::cout << IN_MASK_ADD << std::endl; std::cout << IN_ONESHOT << std::endl; std::cout << IN_IGNORED << std::endl; std::cout << IN_ISDIR << std::endl; std::cout << IN_Q_OVERFLOW << std::endl; std::cout << IN_UNMOUNT << std::endl; */ // bind process broadcast pub zmq::socket_t z_broadcast(z_context, ZMQ_PUB); z_broadcast.bind("inproc://sb_broadcast"); // bind to boxoffice endpoint zmq::socket_t z_boxoffice(z_context, ZMQ_PAIR); z_boxoffice.bind("inproc://sb_bo_main_pair"); // opening boxoffice thread if (SB_MSG_DEBUG) printf("main: opening boxoffice thread\n"); boost::thread bo_thread(boxoffice_thread, &z_context); // wait for signal from boxoffice if (SB_MSG_DEBUG) printf("main: waiting for boxoffice to send exit signal\n"); while(true) { zmq::message_t z_msg; std::stringstream sstream; try { z_boxoffice.recv(&z_msg); sstream << static_cast<char*>(z_msg.data()); } catch(const zmq::error_t &e) { std::cout << "E: " << e.what() << std::endl; } if (s_interrupted) { std::cout << "main: received interrupt, broadcasting signal..." << std::endl; snprintf((char*) z_msg.data(), 4, "%d %d", SB_SIGTYPE_LIFE, SB_SIGLIFE_INTERRUPT); z_broadcast.send(z_msg); break; } int msg_type, msg_signal; sstream >> msg_type >> msg_signal; if (SB_MSG_DEBUG) printf("main: received message: %d %d\n", msg_type, msg_signal); if ( msg_type != SB_SIGTYPE_LIFE || msg_signal != SB_SIGLIFE_EXIT ) return 1; else break; } bo_thread.join(); z_boxoffice.close(); z_broadcast.close(); /* sleep(4); std::cout << "closing thread" << std::endl; zmq::message_t z_msg; snprintf((char*) z_msg.data(), 7, "blabla"); test.send(z_msg); // bo_thread.interrupt(); std::cout << "closed" << std::endl; sleep(1); inotify_rm_watch(fd, wd); close(fd); test.close(); */ z_context.close(); return 0; /* return 0; } // pid > 0 is the parent process else if (pid > 0) { exit(EXIT_SUCCESS); }*/ }<commit_msg>deleted unnecessary, commented-out code from main<commit_after>/* * Blablub * * main.cpp */ #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <zmq.hpp> #include <iostream> #include <fstream> #include <cstring> #include <sstream> #include <boost/thread.hpp> #include <signal.h> #include <sys/inotify.h> #include <poll.h> #include "constants.hpp" #include "boxoffice.hpp" #include "publisher.hpp" static int s_interrupted = 0; static void s_signal_handler (int signal_value) { s_interrupted = 1; } static void s_catch_signals () { #if (!defined(WIN32)) struct sigaction action; action.sa_handler = s_signal_handler; action.sa_flags = 0; sigemptyset (&action.sa_mask); sigaction (SIGINT, &action, NULL); sigaction (SIGTERM, &action, NULL); #endif } void *boxoffice_thread(void *arg) //void *boxoffice_thread(void *arg, void *ctx_) { Boxoffice* bo; bo = Boxoffice::initialize(static_cast<zmq::context_t*>(arg)); /* zmq::context_t* z_context(static_cast<zmq::context_t*>(ctx_)); int* fd = static_cast<int*>(arg); zmq::socket_t test(*z_context, ZMQ_SUB); test.connect("inproc://sb_broadcast"); const char *sub_filter = ""; test.setsockopt(ZMQ_SUBSCRIBE, sub_filter, 0); std::cout << "receiving msg" << std::endl; std::stringstream* sstream = new std::stringstream(); s_recv_in(test, *fd, *sstream); std::cout << sstream->str() << std::endl; delete sstream; test.close(); */ /* pollfd pollfd = {*fd, POLLIN, 0}; poll(&pollfd, 1, -1); std::cout << "blub" << std::endl; length = read( *fd, buffer, SB_IN_BUF_LEN ); if ( length < 0 ) perror("inotify poll"); std::cout << "blub" << std::endl; struct inotify_event* event; event = (struct inotify_event*) &buffer[0]; std::cout << event->mask << std::endl; */ return (NULL); } int main(int argc, char* argv[]) { // FORKING /* pid_t pid, sid; // fork off the SUB process pid = fork(); // if pid < 0 the forking failed if (pid < 0) { exit(EXIT_FAILURE); } // pid==0 is the SUB process itself else if (pid == 0) { umask(0); sid = setsid(); if (sid < 0) { exit(EXIT_FAILURE); } */ // opening zeromq context zmq::context_t z_context(1); // we eagerly initialize the Boxoffice- and Publisher-singleton here, // for thread-safety Boxoffice::getInstance(); Publisher::getInstance(); // catch signals s_catch_signals(); /* std::cout << IN_ACCESS << std::endl; std::cout << IN_ATTRIB << std::endl; std::cout << IN_CLOSE_WRITE << std::endl; std::cout << IN_CLOSE_NOWRITE << std::endl; std::cout << IN_CREATE << std::endl; std::cout << IN_DELETE << std::endl; std::cout << IN_DELETE_SELF << std::endl; std::cout << IN_MODIFY << std::endl; std::cout << IN_MOVE_SELF << std::endl; std::cout << IN_MOVED_FROM << std::endl; std::cout << IN_MOVED_TO << std::endl; std::cout << IN_OPEN << std::endl; std::cout << IN_MOVE << std::endl; std::cout << IN_CLOSE << std::endl; std::cout << IN_DONT_FOLLOW << std::endl; std::cout << IN_EXCL_UNLINK << std::endl; std::cout << IN_MASK_ADD << std::endl; std::cout << IN_ONESHOT << std::endl; std::cout << IN_IGNORED << std::endl; std::cout << IN_ISDIR << std::endl; std::cout << IN_Q_OVERFLOW << std::endl; std::cout << IN_UNMOUNT << std::endl; */ // bind process broadcast pub zmq::socket_t z_broadcast(z_context, ZMQ_PUB); z_broadcast.bind("inproc://sb_broadcast"); // bind to boxoffice endpoint zmq::socket_t z_boxoffice(z_context, ZMQ_PAIR); z_boxoffice.bind("inproc://sb_bo_main_pair"); // opening boxoffice thread if (SB_MSG_DEBUG) printf("main: opening boxoffice thread\n"); boost::thread bo_thread(boxoffice_thread, &z_context); // wait for signal from boxoffice if (SB_MSG_DEBUG) printf("main: waiting for boxoffice to send exit signal\n"); while(true) { zmq::message_t z_msg; std::stringstream sstream; try { z_boxoffice.recv(&z_msg); sstream << static_cast<char*>(z_msg.data()); } catch(const zmq::error_t &e) { std::cout << "E: " << e.what() << std::endl; } if (s_interrupted) { std::cout << "main: received interrupt, broadcasting signal..." << std::endl; snprintf((char*) z_msg.data(), 4, "%d %d", SB_SIGTYPE_LIFE, SB_SIGLIFE_INTERRUPT); z_broadcast.send(z_msg); break; } int msg_type, msg_signal; sstream >> msg_type >> msg_signal; if (SB_MSG_DEBUG) printf("main: received message: %d %d\n", msg_type, msg_signal); if ( msg_type != SB_SIGTYPE_LIFE || msg_signal != SB_SIGLIFE_EXIT ) return 1; else break; } bo_thread.join(); z_boxoffice.close(); z_broadcast.close(); z_context.close(); return 0; /* return 0; } // pid > 0 is the parent process else if (pid > 0) { exit(EXIT_SUCCESS); }*/ }<|endoftext|>
<commit_before>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** main.cpp ** ** -------------------------------------------------------------------------*/ #include <iostream> #include "webrtc/base/ssladapter.h" #include "webrtc/base/thread.h" #include "webrtc/p2p/base/stunserver.h" #include "PeerConnectionManager.h" #include "HttpServerRequestHandler.h" /* --------------------------------------------------------------------------- ** main ** -------------------------------------------------------------------------*/ int main(int argc, char* argv[]) { const char* port = "0.0.0.0:8000"; const char* localstunurl = "127.0.0.1:3478"; const char* stunurl = "stun.l.google.com:19302"; int logLevel = rtc::LERROR; int c = 0; while ((c = getopt (argc, argv, "hH:v::" "S:s::")) != -1) { switch (c) { case 'v': logLevel--; if (optarg) logLevel-=strlen(optarg); break; case 'H': port = optarg; break; case 'S': localstunurl = optarg; stunurl = localstunurl; break; case 's': localstunurl = NULL; if (optarg) stunurl = optarg; break; case 'h': default: std::cout << argv[0] << " [-H http port] [-S embeded stun address] -[v[v]]" << std::endl; std::cout << argv[0] << " [-H http port] [-s externel stun address] -[v[v]]" << std::endl; std::cout << "\t -v[v[v]] : verbosity" << std::endl; std::cout << "\t -H [hostname:]port : HTTP server binding (default " << port << ")" << std::endl; std::cout << "\t -S stun_address : start embedeed STUN server bind to address (default " << localstunurl << ")" << std::endl; std::cout << "\t -s[stun_address] : use an external STUN server (default " << stunurl << ")" << std::endl; exit(0); } } rtc::LogMessage::LogToDebug((rtc::LoggingSeverity)logLevel); rtc::LogMessage::LogTimestamps(); rtc::LogMessage::LogThreads(); std::cout << "Logger level:" << rtc::LogMessage::GetMinLogSeverity() << std::endl; rtc::Thread* thread = rtc::Thread::Current(); rtc::InitializeSSL(); // webrtc server PeerConnectionManager webRtcServer(stunurl); if (!webRtcServer.InitializePeerConnection()) { std::cout << "Cannot Initialize WebRTC server" << std::endl; } else { // http server rtc::HttpListenServer httpServer; rtc::SocketAddress http_addr; http_addr.FromString(port); int ret = httpServer.Listen(http_addr); if (ret != 0) { std::cout << "Cannot Initialize start HTTP server " << strerror(ret) << std::endl; } else { // connect httpserver to a request handler HttpServerRequestHandler http(&httpServer, &webRtcServer); std::cout << "HTTP Listening at " << http_addr.ToString() << std::endl; if (localstunurl != NULL) { // STUN server rtc::SocketAddress server_addr; server_addr.FromString(localstunurl); std::unique_ptr<cricket::StunServer> stunserver; rtc::AsyncUDPSocket* server_socket = rtc::AsyncUDPSocket::Create(thread->socketserver(), server_addr); if (server_socket) { stunserver.reset(new cricket::StunServer(server_socket)); std::cout << "STUN Listening at " << server_addr.ToString() << std::endl; } } // mainloop while(thread->ProcessMessages(10)); } } rtc::CleanupSSL(); return 0; } <commit_msg>fix local STUN server that was immediatly stoped<commit_after>/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** main.cpp ** ** -------------------------------------------------------------------------*/ #include <iostream> #include "webrtc/base/ssladapter.h" #include "webrtc/base/thread.h" #include "webrtc/p2p/base/stunserver.h" #include "PeerConnectionManager.h" #include "HttpServerRequestHandler.h" /* --------------------------------------------------------------------------- ** main ** -------------------------------------------------------------------------*/ int main(int argc, char* argv[]) { const char* port = "0.0.0.0:8000"; const char* localstunurl = "127.0.0.1:3478"; const char* stunurl = "stun.l.google.com:19302"; int logLevel = rtc::LERROR; int c = 0; while ((c = getopt (argc, argv, "hH:v::" "S:s::")) != -1) { switch (c) { case 'v': logLevel--; if (optarg) logLevel-=strlen(optarg); break; case 'H': port = optarg; break; case 'S': localstunurl = optarg; stunurl = localstunurl; break; case 's': localstunurl = NULL; if (optarg) stunurl = optarg; break; case 'h': default: std::cout << argv[0] << " [-H http port] [-S embeded stun address] -[v[v]]" << std::endl; std::cout << argv[0] << " [-H http port] [-s externel stun address] -[v[v]]" << std::endl; std::cout << "\t -v[v[v]] : verbosity" << std::endl; std::cout << "\t -H [hostname:]port : HTTP server binding (default " << port << ")" << std::endl; std::cout << "\t -S stun_address : start embedeed STUN server bind to address (default " << localstunurl << ")" << std::endl; std::cout << "\t -s[stun_address] : use an external STUN server (default " << stunurl << ")" << std::endl; exit(0); } } rtc::LogMessage::LogToDebug((rtc::LoggingSeverity)logLevel); rtc::LogMessage::LogTimestamps(); rtc::LogMessage::LogThreads(); std::cout << "Logger level:" << rtc::LogMessage::GetMinLogSeverity() << std::endl; rtc::Thread* thread = rtc::Thread::Current(); rtc::InitializeSSL(); // webrtc server PeerConnectionManager webRtcServer(stunurl); if (!webRtcServer.InitializePeerConnection()) { std::cout << "Cannot Initialize WebRTC server" << std::endl; } else { // http server rtc::HttpListenServer httpServer; rtc::SocketAddress http_addr; http_addr.FromString(port); int ret = httpServer.Listen(http_addr); if (ret != 0) { std::cout << "Cannot Initialize start HTTP server " << strerror(ret) << std::endl; } else { // connect httpserver to a request handler HttpServerRequestHandler http(&httpServer, &webRtcServer); std::cout << "HTTP Listening at " << http_addr.ToString() << std::endl; // start STUN server if needed std::unique_ptr<cricket::StunServer> stunserver; if (localstunurl != NULL) { rtc::SocketAddress server_addr; server_addr.FromString(localstunurl); rtc::AsyncUDPSocket* server_socket = rtc::AsyncUDPSocket::Create(thread->socketserver(), server_addr); if (server_socket) { stunserver.reset(new cricket::StunServer(server_socket)); std::cout << "STUN Listening at " << server_addr.ToString() << std::endl; } } // mainloop thread->Run(); } } rtc::CleanupSSL(); return 0; } <|endoftext|>
<commit_before>#pragma once #include "game/bindings/bind_game_and_augs.h" #include "augs/global_libraries.h" #include "game/multiverse.h" #include "game/game_window.h" #include "game/resources/manager.h" #include "game/scene_managers/testbed.h" #include "game/scene_managers/resource_setups/all.h" #include "game/types_specification/all_component_includes.h" int main(int argc, char** argv) { augs::global_libraries::init(); augs::global_libraries::run_googletest(); game_window window; window.call_window_script("config.lua"); resource_manager.destroy_everything(); resource_setups::load_standard_everything(); multiverse hypersomnia; hypersomnia.main_cosmos.settings.screen_size = vec2i(window.window.get_screen_rect()); window.window.set_as_current(); bool should_quit = false; if (!hypersomnia.main_cosmos_player.try_to_load_and_replay_recording("recorded.inputs")) hypersomnia.main_cosmos_player.record_and_save_this_session("sessions/", "recorded.inputs"); while (!should_quit) { auto new_entropy = window.collect_entropy(); for (auto& n : new_entropy.local) { if (n.key == augs::window::event::keys::ESC && n.key_event == augs::window::event::key_changed::PRESSED) { should_quit = true; } } hypersomnia.control(new_entropy); hypersomnia.simulate(); hypersomnia.view(window); } augs::global_libraries::deinit(); return 0; }<commit_msg>fixed main<commit_after>#pragma once #include "game/bindings/bind_game_and_augs.h" #include "augs/global_libraries.h" #include "game/multiverse.h" #include "game/game_window.h" #include "game/resources/manager.h" #include "game/scene_managers/testbed.h" #include "game/scene_managers/resource_setups/all.h" #include "game/types_specification/all_component_includes.h" #include "game/entity_relations.h" int main(int argc, char** argv) { augs::global_libraries::init(); augs::global_libraries::run_googletest(); game_window window; window.call_window_script("config.lua"); resource_manager.destroy_everything(); resource_setups::load_standard_everything(); multiverse hypersomnia; hypersomnia.main_cosmos.settings.screen_size = vec2i(window.window.get_screen_rect()); hypersomnia.populate_cosmoi(); window.window.set_as_current(); bool should_quit = false; if (!hypersomnia.main_cosmos_player.try_to_load_and_replay_recording("recorded.inputs")) hypersomnia.main_cosmos_player.record_and_save_this_session("sessions/", "recorded.inputs"); while (!should_quit) { auto new_entropy = window.collect_entropy(); for (auto& n : new_entropy.local) { if (n.key == augs::window::event::keys::ESC && n.key_event == augs::window::event::key_changed::PRESSED) { should_quit = true; } } hypersomnia.control(new_entropy); hypersomnia.simulate(); hypersomnia.view(window); } augs::global_libraries::deinit(); return 0; }<|endoftext|>
<commit_before>/** @file @brief Save data from database to RAM (or hard drive in future version). @author Yi Zhao */ #include "main.h" /** @brief Save data from MYSQL_RES to RAM. @see localrow @remark Data saved in linked list.\n Usage:\n MYSQL_RES *result=mysql_store_result(mysql_conn);\n localrow *localresult;\n int res=make_mysqlres_local(&localresult,result); */ int make_mysqlres_local(localrow **localresult,MYSQL_RES *result_t){ //FILE *fout=fopen("tmp/out.tmp","w"); FILE *fout=tmpfile(); if(fout==NULL){ printf("no!!!!!!!"); return -1; } mysql_data_seek(result_t,0); MYSQL_ROW sql_row; while((sql_row=mysql_fetch_row(result_t))){ int i; for(i=0;i<8-1;i++){ fprintf(fout,"%s\t",sql_row[i]); }fprintf(fout,"%s\n",sql_row[i]); } fclose(fout); return 0; /* int count=0; mysql_data_seek(result_t,0); localrow **p=localresult; MYSQL_ROW sql_row; while((sql_row=mysql_fetch_row(result_t))){ *p=(localrow*)malloc(sizeof(localrow)); for(int i=0;i<8;i++){ strcpy((*p)->row[i],sql_row[i]); } p=&((*p)->next); count++; } *p=NULL; return count;*/ } /** @brief Free data on RAM. @see localrow */ void free_mysqlres_local(localrow *localresult){ while(localresult){ localrow *p=localresult; localresult=p->next; free(p); } } /** @brief Get number of saved sgRNA-Info on RAM. @see localrow */ int localres_count(localrow *lr){ int i=0; while(lr){ i++; lr=lr->next; if(i>NODE_SIZE) return -1; } return i; } <commit_msg>nobingfa<commit_after>/** @file @brief Save data from database to RAM (or hard drive in future version). @author Yi Zhao */ #include "main.h" /** @brief Save data from MYSQL_RES to RAM. @see localrow @remark Data saved in linked list.\n Usage:\n MYSQL_RES *result=mysql_store_result(mysql_conn);\n localrow *localresult;\n int res=make_mysqlres_local(&localresult,result); */ FILE *make_mysqlres_local(localrow **localresult,MYSQL_RES *result_t){ FILE *fout=fopen("tmp/out.tmp","w"); //FILE *fout=tmpfile(); if(fout==NULL){ printf("no!!!!!!!"); return -1; } mysql_data_seek(result_t,0); MYSQL_ROW sql_row; while((sql_row=mysql_fetch_row(result_t))){ int i; for(i=0;i<8-1;i++){ fprintf(fout,"%s\t",sql_row[i]); }fprintf(fout,"%s\n",sql_row[i]); } fclose(fout); return fout; /* int count=0; mysql_data_seek(result_t,0); localrow **p=localresult; MYSQL_ROW sql_row; while((sql_row=mysql_fetch_row(result_t))){ *p=(localrow*)malloc(sizeof(localrow)); for(int i=0;i<8;i++){ strcpy((*p)->row[i],sql_row[i]); } p=&((*p)->next); count++; } *p=NULL; return count;*/ } /** @brief Free data on RAM. @see localrow */ void free_mysqlres_local(localrow *localresult){ //fclose(fout); /*while(localresult){ localrow *p=localresult; localresult=p->next; free(p); }*/ } /** @brief Get number of saved sgRNA-Info on RAM. @see localrow */ int localres_count(localrow *lr){ int i=0; while(lr){ i++; lr=lr->next; if(i>NODE_SIZE) return -1; } return i; } <|endoftext|>
<commit_before>#include "../core_include/api.h" #include "../core_include/resource.h" #include "../core_include/rect.h" #include "../core_include/bitmap.h" #include "../core_include/surface.h" void c_bitmap::draw_bitmap(c_surface* surface, int z_order, const BITMAP_INFO *pBitmap, int x, int y, unsigned int mask_rgb) { if (0 == pBitmap) { return; } unsigned short* lower_fb = 0; int lower_fb_width = surface->m_width; if (z_order >= Z_ORDER_LEVEL_1) { lower_fb = surface->m_frame_layers[z_order - 1].fb; } unsigned int mask_rgb_16 = GL_RGB_32_to_16(mask_rgb); int xsize = pBitmap->XSize; int ysize = pBitmap->YSize; const unsigned short* pData = (const unsigned short*)pBitmap->pData; for (int j = 0; j < ysize; j++) { for (int i = 0; i < xsize; i++) { unsigned int rgb = *pData++; if (mask_rgb_16 == rgb) { if (lower_fb) {//restore lower layer surface->draw_pixel(x + i, y + j, GL_RGB_16_to_32(lower_fb[(y + j) * lower_fb_width + x + i]), z_order); } } else { surface->draw_pixel(x + i, y + j, GL_RGB_16_to_32(rgb), z_order); } } } } void c_bitmap::draw_bitmap(c_surface* surface, int z_order, const BITMAP_INFO* pBitmap, int x, int y, int src_x, int src_y, int width, int height, unsigned int mask_rgb) { if (0 == pBitmap || (src_x + width > pBitmap->XSize) || (src_y + height > pBitmap->XSize)) { return; } unsigned short* lower_fb = 0; int lower_fb_width = surface->m_width; if (z_order >= Z_ORDER_LEVEL_1) { lower_fb = surface->m_frame_layers[z_order - 1].fb; } unsigned int mask_rgb_16 = GL_RGB_32_to_16(mask_rgb); const unsigned short* pData = (const unsigned short*)pBitmap->pData; for (int j = 0; j < height; j++) { const unsigned short* p = &pData[src_x + (src_y + j) * pBitmap->XSize]; for (int i = 0; i < width; i++) { unsigned int rgb = *p++; if (mask_rgb_16 == rgb) { if (lower_fb) {//restore lower layer surface->draw_pixel(x + i, y + j, GL_RGB_16_to_32(lower_fb[(y + j) * lower_fb_width + x + i]), z_order); } } else { surface->draw_pixel(x + i, y + j, GL_RGB_16_to_32(rgb), z_order); } } } } <commit_msg>fix bitmap issue<commit_after>#include "../core_include/api.h" #include "../core_include/resource.h" #include "../core_include/rect.h" #include "../core_include/bitmap.h" #include "../core_include/surface.h" void c_bitmap::draw_bitmap(c_surface* surface, int z_order, const BITMAP_INFO *pBitmap, int x, int y, unsigned int mask_rgb) { if (0 == pBitmap) { return; } unsigned short* lower_fb = 0; int lower_fb_width = surface->m_width; if (z_order >= Z_ORDER_LEVEL_1) { lower_fb = surface->m_frame_layers[z_order - 1].fb; } unsigned int mask_rgb_16 = GL_RGB_32_to_16(mask_rgb); int xsize = pBitmap->XSize; int ysize = pBitmap->YSize; const unsigned short* pData = (const unsigned short*)pBitmap->pData; for (int j = 0; j < ysize; j++) { for (int i = 0; i < xsize; i++) { unsigned int rgb = *pData++; if (mask_rgb_16 == rgb) { if (lower_fb) {//restore lower layer surface->draw_pixel(x + i, y + j, GL_RGB_16_to_32(lower_fb[(y + j) * lower_fb_width + x + i]), z_order); } } else { surface->draw_pixel(x + i, y + j, GL_RGB_16_to_32(rgb), z_order); } } } } void c_bitmap::draw_bitmap(c_surface* surface, int z_order, const BITMAP_INFO* pBitmap, int x, int y, int src_x, int src_y, int width, int height, unsigned int mask_rgb) { if (0 == pBitmap || (src_x + width > pBitmap->XSize) || (src_y + height > pBitmap->YSize)) { return; } unsigned short* lower_fb = 0; int lower_fb_width = surface->m_width; if (z_order >= Z_ORDER_LEVEL_1) { lower_fb = surface->m_frame_layers[z_order - 1].fb; } unsigned int mask_rgb_16 = GL_RGB_32_to_16(mask_rgb); const unsigned short* pData = (const unsigned short*)pBitmap->pData; for (int j = 0; j < height; j++) { const unsigned short* p = &pData[src_x + (src_y + j) * pBitmap->XSize]; for (int i = 0; i < width; i++) { unsigned int rgb = *p++; if (mask_rgb_16 == rgb) { if (lower_fb) {//restore lower layer surface->draw_pixel(x + i, y + j, GL_RGB_16_to_32(lower_fb[(y + j) * lower_fb_width + x + i]), z_order); } } else { surface->draw_pixel(x + i, y + j, GL_RGB_16_to_32(rgb), z_order); } } } } <|endoftext|>
<commit_before>#include <limits> #include <algorithm> #include <array> #include <iomanip> #include <curl/curl.h> #include <memory> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> #include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string update_check(""); const std::string file_checksum(const std::string &path); size_t writefunction(const char *ptr, size_t size, size_t nmemb, void *userdata) { std::string *s = static_cast<std::string *>(userdata); s->append(ptr, size * nmemb); return size * nmemb; } std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } class Target { public: enum class Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } const std::string checksum() const { return m_checksum; } void fetch() { std::cout << "Statting target " << name() << "..."; std::string path; std::fstream fs(name(), std::ios_base::in); if (!fs.good()) { fs.close(); std::cout << " doesn't exist, creating new." << std::endl; auto elems = split(name(), '/'); for (size_t i = 0, k = elems.size(); i < k; ++i) { const std::string &s(elems[i]); if (s.size() && s != ".") { path.append((i > 0 ? "/" : "") + s); // i indicates a directory. if (i < k - 1) { auto status = mkdir(path.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err != std::errc::file_exists) { std::cout << "error making dir: " << path << ": " << err.message() << std::endl; } } } } } fs.open(path, std::ios_base::out); if (!fs.good()) { fs.close(); std::cout << "Failed to create file: " << path << std::endl; } else { fs.close(); do_fetch(); return; } } if (fs.good()) { fs.close(); if (status() == Status::Current) { std::cout << " already up to date." << std::endl; } else { std::cout << " outdated, downloading new." << std::endl; do_fetch(); } } } Status status() { std::ifstream is(name()); if (!is.good()) { return Status::Nonexistent; } is.close(); auto calcsum(file_checksum(name())); if (calcsum == checksum()) { return Status::Current; } else { return Status::Outdated; } } private: void do_fetch() { std::string s; std::shared_ptr<CURL *> phandle = std::make_shared<CURL *>(curl_easy_init()); std::string url(patch_dir + name()); curl_easy_setopt(*phandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction); curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &s); //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0); curl_easy_perform(*phandle); curl_easy_cleanup(*phandle); phandle.reset(); std::ofstream ofs(name()); if (ofs.good()) { ofs << s; ofs.close(); std::cout << "Finished downloading " << name() << std::endl; } else { std::cout << "Couldn't write to " << name() << std::endl; } } std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } class CurlGlobalInit { public: CurlGlobalInit() { curl_global_init(CURL_GLOBAL_ALL); } ~CurlGlobalInit() { curl_global_cleanup(); } }; const std::string file_checksum(const std::string &path) { #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ifstream::binary); if (!is.good()) { std::cout << "Couldn't open file " << path << " for checksumming." << std::endl; return std::string(); } const int length = 8192; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount()); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); for (unsigned char c : result) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); } /* std::for_each(std::begin(result), std::end(result), [&calcsum](unsigned char c) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); }); */ return calcsum.str(); } struct Options { bool checksum(const std::string &val) { return val == "checksum"; } }; bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = tolower(c); } while (c != 'y' && c != 'n'); return c == 'y'; } int main(int argc, char *argv[]) { CurlGlobalInit curl_global; const std::string update_check("https://raw.github.com/commonquail/efulauncher/updatecheck/versioncheck"); std::string fetch; std::shared_ptr<CURL *> phandle = std::make_shared<CURL *>(curl_easy_init()); curl_easy_setopt(*phandle, CURLOPT_URL, update_check.c_str()); curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction); curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch); //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0); curl_easy_perform(*phandle); curl_easy_cleanup(*phandle); Options opts; std::vector<std::string> lines(split(fetch, '\n')); fetch.clear(); for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto keyvals(split(*beg, '=')); if (opts.checksum(keyvals[0])) { const std::string checksum_test(keyvals[keyvals.size() - 1]); if (checksum_test != file_checksum(argv[0])) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use the latest launcher."\ " Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; std::cout << "Done." << std::endl; } } } } phandle = std::make_shared<CURL *>(curl_easy_init()); curl_easy_setopt(*phandle, CURLOPT_URL, listing.c_str()); curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction); curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch); //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0); curl_easy_perform(*phandle); curl_easy_cleanup(*phandle); phandle.reset(); lines = split(fetch, '\n'); std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto data(split(*beg, '@')); Target t(data[0], data[data.size() - 1]); auto status = t.status(); if (status == Target::Status::Nonexistent) { new_targets.push_back(std::move(t)); } else if (status == Target::Status::Outdated) { old_targets.push_back(std::move(t)); } } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; for (auto &t : new_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; for (auto &t : old_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No targets out of date." << std::endl; } #ifndef DEBUG for (auto &t : new_targets) { t.fetch(); } for (auto &t : old_targets) { t.fetch(); } #endif return 0; } <commit_msg>Make class Options a namespace instead.<commit_after>#include <limits> #include <algorithm> #include <array> #include <iomanip> #include <curl/curl.h> #include <memory> #include <string> #include <sstream> #include <iostream> #include <fstream> #include <vector> #include <sys/stat.h> #include <cerrno> #include <cstring> #include <system_error> #include <openssl/md5.h> #include <openssl/sha.h> #include <openssl/evp.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <fcntl.h> #include <string.h> const std::string listing("http://nwn.efupw.com/rootdir/index.dat"); const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/"); const std::string update_check(""); const std::string file_checksum(const std::string &path); size_t writefunction(const char *ptr, size_t size, size_t nmemb, void *userdata) { std::string *s = static_cast<std::string *>(userdata); s->append(ptr, size * nmemb); return size * nmemb; } std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; return split(s, delim, elems); } class Target { public: enum class Status { Nonexistent, Outdated, Current }; explicit Target(const std::string &name, const std::string &checksum): m_name(name.find_first_of('/') == std::string::npos ? name : name, name.find_first_of('/') + 1, name.size() - 1), m_checksum(checksum) {} std::string name() const { return m_name; } const std::string checksum() const { return m_checksum; } void fetch() { std::cout << "Statting target " << name() << "..."; std::string path; std::fstream fs(name(), std::ios_base::in); if (!fs.good()) { fs.close(); std::cout << " doesn't exist, creating new." << std::endl; auto elems = split(name(), '/'); for (size_t i = 0, k = elems.size(); i < k; ++i) { const std::string &s(elems[i]); if (s.size() && s != ".") { path.append((i > 0 ? "/" : "") + s); // i indicates a directory. if (i < k - 1) { auto status = mkdir(path.c_str(), S_IRWXU); if (status == -1) { std::error_code err(errno, std::generic_category()); if (err != std::errc::file_exists) { std::cout << "error making dir: " << path << ": " << err.message() << std::endl; } } } } } fs.open(path, std::ios_base::out); if (!fs.good()) { fs.close(); std::cout << "Failed to create file: " << path << std::endl; } else { fs.close(); do_fetch(); return; } } if (fs.good()) { fs.close(); if (status() == Status::Current) { std::cout << " already up to date." << std::endl; } else { std::cout << " outdated, downloading new." << std::endl; do_fetch(); } } } Status status() { std::ifstream is(name()); if (!is.good()) { return Status::Nonexistent; } is.close(); auto calcsum(file_checksum(name())); if (calcsum == checksum()) { return Status::Current; } else { return Status::Outdated; } } private: void do_fetch() { std::string s; std::shared_ptr<CURL *> phandle = std::make_shared<CURL *>(curl_easy_init()); std::string url(patch_dir + name()); curl_easy_setopt(*phandle, CURLOPT_URL, url.c_str()); curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction); curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &s); //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0); curl_easy_perform(*phandle); curl_easy_cleanup(*phandle); phandle.reset(); std::ofstream ofs(name()); if (ofs.good()) { ofs << s; ofs.close(); std::cout << "Finished downloading " << name() << std::endl; } else { std::cout << "Couldn't write to " << name() << std::endl; } } std::string m_name; std::string m_checksum; }; std::ostream& operator<<(std::ostream &os, const Target &t) { return os << "name: " << t.name() << ", checksum: " << t.checksum(); } class CurlGlobalInit { public: CurlGlobalInit() { curl_global_init(CURL_GLOBAL_ALL); } ~CurlGlobalInit() { curl_global_cleanup(); } }; const std::string file_checksum(const std::string &path) { #ifdef md_md5 auto md = EVP_md5(); const int md_len = MD5_DIGEST_LENGTH; #else auto md = EVP_sha1(); const int md_len = SHA_DIGEST_LENGTH; #endif std::array<unsigned char, md_len> result; EVP_MD_CTX *mdctx = nullptr; std::ifstream is(path, std::ifstream::binary); if (!is.good()) { std::cout << "Couldn't open file " << path << " for checksumming." << std::endl; return std::string(); } const int length = 8192; std::array<unsigned char, length> buffer; auto buf = reinterpret_cast<char *>(buffer.data()); mdctx = EVP_MD_CTX_create(); int status = EVP_DigestInit_ex(mdctx, md, nullptr); while (status && is) { is.read(buf, length); status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount()); } status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr); EVP_MD_CTX_destroy(mdctx); std::stringstream calcsum; calcsum << std::setfill('0'); for (unsigned char c : result) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); } /* std::for_each(std::begin(result), std::end(result), [&calcsum](unsigned char c) { calcsum << std::hex << std::setw(2) << static_cast<unsigned int>(c); }); */ return calcsum.str(); } namespace Options { bool checksum(const std::string &val) { return val == "checksum"; } }; bool confirm() { char c; do { std::cin >> c; std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); c = tolower(c); } while (c != 'y' && c != 'n'); return c == 'y'; } int main(int argc, char *argv[]) { CurlGlobalInit curl_global; const std::string update_check("https://raw.github.com/commonquail/efulauncher/updatecheck/versioncheck"); std::string fetch; std::shared_ptr<CURL *> phandle = std::make_shared<CURL *>(curl_easy_init()); curl_easy_setopt(*phandle, CURLOPT_URL, update_check.c_str()); curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction); curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch); //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0); curl_easy_perform(*phandle); curl_easy_cleanup(*phandle); std::vector<std::string> lines(split(fetch, '\n')); fetch.clear(); for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto keyvals(split(*beg, '=')); if (Options::checksum(keyvals[0])) { const std::string checksum_test(keyvals[keyvals.size() - 1]); if (checksum_test != file_checksum(argv[0])) { std::cout << "A new version of the launcher is available."\ " Would you like to download it (y/n)?" << std::endl; bool download(confirm()); if (!download) { std::cout << "It is strongly recommended to always use the latest launcher."\ " Would you like to download it (y/n)?" << std::endl; download = confirm(); } if (download) { // Download. std::cout << "Downloading new launcher..." << std::endl; std::cout << "Done." << std::endl; } } } } phandle = std::make_shared<CURL *>(curl_easy_init()); curl_easy_setopt(*phandle, CURLOPT_URL, listing.c_str()); curl_easy_setopt(*phandle, CURLOPT_WRITEFUNCTION, &writefunction); curl_easy_setopt(*phandle, CURLOPT_WRITEDATA, &fetch); //curl_easy_setopt(*phandle, CURLOPT_NOPROGRESS, 0); curl_easy_perform(*phandle); curl_easy_cleanup(*phandle); phandle.reset(); lines = split(fetch, '\n'); std::vector<Target> new_targets, old_targets; for (auto beg = std::begin(lines), end = std::end(lines); beg != end; ++beg) { auto data(split(*beg, '@')); Target t(data[0], data[data.size() - 1]); auto status = t.status(); if (status == Target::Status::Nonexistent) { new_targets.push_back(std::move(t)); } else if (status == Target::Status::Outdated) { old_targets.push_back(std::move(t)); } } if (new_targets.size()) { std::cout << "New targets: " << new_targets.size() << std::endl; for (auto &t : new_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No new targets." << std::endl; } if (old_targets.size()) { std::cout << "Outdated targets: " << old_targets.size() << std::endl; for (auto &t : old_targets) { std::cout << "- " << t.name() << std::endl; } } else { std::cout << "No targets out of date." << std::endl; } #ifndef DEBUG for (auto &t : new_targets) { t.fetch(); } for (auto &t : old_targets) { t.fetch(); } #endif return 0; } <|endoftext|>
<commit_before>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/CopasiSE/CopasiSE.cpp,v $ $Revision: 1.18 $ $Name: $ $Author: shoops $ $Date: 2005/08/08 17:28:04 $ End CVS Header */ // Main // // (C) Stefan Hoops 2002 // #include <stdlib.h> #include <sstream> #include <string> #include <iostream> #define COPASI_MAIN #define COPASI_TRACE_CONSTRUCTION #include "copasi.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "utilities/CCopasiMessage.h" #include "utilities/CCopasiException.h" #include "utilities/CCopasiTask.h" #include "utilities/CCopasiProblem.h" #include "commandline/COptionParser.h" #include "commandline/COptions.h" #include "function/CFunctionDB.h" #include "function/CEvaluationTree.h" #include "utilities/CopasiTime.h" #include "randomGenerator/CRandom.h" #include "report/CKeyFactory.h" int main(int argc, char *argv[]) { try { // Parse the commandline options COptions::init(argc, argv); } catch (copasi::autoexcept &e) { switch (e.get_autothrow_id()) { case copasi::autothrow_help: std::cout << "Usage: " << argv[0] << " [options]\n"; std::cout << e.what(); } return 1; } catch (copasi::option_error &e) { std::cerr << argv[0] << ": " << e.what() << "\n"; std::cerr << e.get_help_comment() << std::endl; return 1; } try { // Create the root container. CCopasiContainer::init(); // Create the global data model. CCopasiDataModel::Global = new CCopasiDataModel; #ifdef XXXX CCallParameters<C_FLOAT64> Variables(20); unsigned C_INT32 j, i, imax = Variables.size(); CRandom * pRandom = CRandom::createGenerator(); for (i = 0; i < imax; i++) { C_FLOAT64 * pValue = new C_FLOAT64; *pValue = 100.0 * pRandom->getRandomOO(); Variables[i].value = pValue; } CCopasiTimer * pCPU = const_cast<CCopasiTimer *>(static_cast<const CCopasiTimer *>(CCopasiContainer::Root->getObject((std::string)"CN=Root,Timer=CPU Time"))); CCopasiTimer * pWall = const_cast<CCopasiTimer *>(static_cast<const CCopasiTimer *>(CCopasiContainer::Root->getObject((std::string)"CN=Root,Timer=Wall Clock Time"))); CCopasiVectorN< CEvaluationTree > & Functions = CCopasiDataModel::Global->getFunctionList()->loadedFunctions(); CFunction * pFunction; for (i = 0, imax = Functions.size(); i < imax; i++) { pFunction = dynamic_cast<CFunction *>(Functions[i]); if (pFunction->getType() != CEvaluationTree::MassAction) for (j = 0; j < 100000; j++) pFunction->calcValue(Variables); } pCPU->actualize(); pWall->actualize(); std::cout << "CPU time: "; pCPU->print(&std::cout); std::cout << std::endl; std::cout << "Wall time: "; pWall->print(&std::cout); std::cout << std::endl; #endif // XXXX #ifdef XXXX CEvaluationTree Expression; Expression.setInfix("5**-sin(x)"); Expression.setInfix("a*5.0/-b"); Expression.setInfix("EXPONENTIALE+b*c"); Expression.setInfix("4.0*\"PI+b"); Expression.setInfix("2*(3+b)"); #endif const COptions::nonOptionType & Files = COptions::getNonOptions(); if (!COptions::compareValue("ImportSBML", std::string(""))) { // Import the SBML File std::string ImportSBML; COptions::getValue("ImportSBML", ImportSBML); CCopasiDataModel::Global->importSBML(ImportSBML); // Save the COPASI File, which is the only thing to do. std::string Save; COptions::getValue("Save", Save); CCopasiDataModel::Global->saveModel(Save); } COptions::nonOptionType::const_iterator it = Files.begin(); COptions::nonOptionType::const_iterator end = Files.end(); for (; it != end; ++it) { CCopasiDataModel::Global->loadModel(*it); // Check whether exporting to SBML is requested. if (!COptions::compareValue("ExportSBML", std::string(""))) { // Export the SBML File std::string ExportSBML; COptions::getValue("ExportSBML", ExportSBML); CCopasiDataModel::Global->exportSBML(ExportSBML); // Since only one export file name can be specified we // stop execution. return 0; } CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList(); unsigned C_INT32 i, imax = TaskList.size(); for (i = 0; i < imax; i++) if (TaskList[i]->isScheduled()) { TaskList[i]->getProblem()->setModel(CCopasiDataModel::Global->getModel()); TaskList[i]->initialize(); TaskList[i]->process(); TaskList[i]->restore(); } // Check whether a file for saving the resulting model is given if (!COptions::compareValue("Save", std::string(""))) { std::string Save; COptions::getValue("Save", Save); CCopasiDataModel::Global->saveModel(Save); // Since only one save file name can be specified we // stop execution. return 0; } // CCopasiDataModel::Global->saveModel(""); } //#endif // XXXX } catch (CCopasiException Exception) { std::cout << Exception.getMessage().getText() << std::endl; } pdelete(CCopasiDataModel::Global); pdelete(CCopasiContainer::Root); //std::cout << "Leaving main program." << std::endl; return 0; } <commit_msg>Added missing includes.<commit_after>/* Begin CVS Header $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/CopasiSE/CopasiSE.cpp,v $ $Revision: 1.19 $ $Name: $ $Author: shoops $ $Date: 2005/08/08 18:03:10 $ End CVS Header */ // Main // // (C) Stefan Hoops 2002 // #include <stdlib.h> #include <sstream> #include <string> #include <iostream> #define COPASI_MAIN #define COPASI_TRACE_CONSTRUCTION #include "copasi.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "utilities/CCopasiMessage.h" #include "utilities/CCopasiException.h" #include "utilities/CCopasiTask.h" #include "utilities/CCopasiProblem.h" #include "commandline/COptionParser.h" #include "commandline/COptions.h" #include "function/CFunctionDB.h" #include "function/CEvaluationTree.h" #include "function/CFunction.h" #include "randomGenerator/CRandom.h" #include "report/CCopasiTimer.h" #include "report/CKeyFactory.h" int main(int argc, char *argv[]) { try { // Parse the commandline options COptions::init(argc, argv); } catch (copasi::autoexcept &e) { switch (e.get_autothrow_id()) { case copasi::autothrow_help: std::cout << "Usage: " << argv[0] << " [options]\n"; std::cout << e.what(); } return 1; } catch (copasi::option_error &e) { std::cerr << argv[0] << ": " << e.what() << "\n"; std::cerr << e.get_help_comment() << std::endl; return 1; } try { // Create the root container. CCopasiContainer::init(); // Create the global data model. CCopasiDataModel::Global = new CCopasiDataModel; #ifdef XXXX CCallParameters<C_FLOAT64> Variables(20); unsigned C_INT32 j, i, imax = Variables.size(); CRandom * pRandom = CRandom::createGenerator(); for (i = 0; i < imax; i++) { C_FLOAT64 * pValue = new C_FLOAT64; *pValue = 100.0 * pRandom->getRandomOO(); Variables[i].value = pValue; } CCopasiTimer * pCPU = const_cast<CCopasiTimer *>(static_cast<const CCopasiTimer *>(CCopasiContainer::Root->getObject((std::string)"CN=Root,Timer=CPU Time"))); CCopasiTimer * pWall = const_cast<CCopasiTimer *>(static_cast<const CCopasiTimer *>(CCopasiContainer::Root->getObject((std::string)"CN=Root,Timer=Wall Clock Time"))); CCopasiVectorN< CEvaluationTree > & Functions = CCopasiDataModel::Global->getFunctionList()->loadedFunctions(); CFunction * pFunction; for (i = 0, imax = Functions.size(); i < imax; i++) { pFunction = dynamic_cast<CFunction *>(Functions[i]); if (pFunction->getType() != CEvaluationTree::MassAction) for (j = 0; j < 100000; j++) pFunction->calcValue(Variables); } pCPU->actualize(); pWall->actualize(); std::cout << "CPU time: "; pCPU->print(&std::cout); std::cout << std::endl; std::cout << "Wall time: "; pWall->print(&std::cout); std::cout << std::endl; #endif // XXXX #ifdef XXXX CEvaluationTree Expression; Expression.setInfix("5**-sin(x)"); Expression.setInfix("a*5.0/-b"); Expression.setInfix("EXPONENTIALE+b*c"); Expression.setInfix("4.0*\"PI+b"); Expression.setInfix("2*(3+b)"); #endif const COptions::nonOptionType & Files = COptions::getNonOptions(); if (!COptions::compareValue("ImportSBML", std::string(""))) { // Import the SBML File std::string ImportSBML; COptions::getValue("ImportSBML", ImportSBML); CCopasiDataModel::Global->importSBML(ImportSBML); // Save the COPASI File, which is the only thing to do. std::string Save; COptions::getValue("Save", Save); CCopasiDataModel::Global->saveModel(Save); } COptions::nonOptionType::const_iterator it = Files.begin(); COptions::nonOptionType::const_iterator end = Files.end(); for (; it != end; ++it) { CCopasiDataModel::Global->loadModel(*it); // Check whether exporting to SBML is requested. if (!COptions::compareValue("ExportSBML", std::string(""))) { // Export the SBML File std::string ExportSBML; COptions::getValue("ExportSBML", ExportSBML); CCopasiDataModel::Global->exportSBML(ExportSBML); // Since only one export file name can be specified we // stop execution. return 0; } CCopasiVectorN< CCopasiTask > & TaskList = * CCopasiDataModel::Global->getTaskList(); unsigned C_INT32 i, imax = TaskList.size(); for (i = 0; i < imax; i++) if (TaskList[i]->isScheduled()) { TaskList[i]->getProblem()->setModel(CCopasiDataModel::Global->getModel()); TaskList[i]->initialize(); TaskList[i]->process(); TaskList[i]->restore(); } // Check whether a file for saving the resulting model is given if (!COptions::compareValue("Save", std::string(""))) { std::string Save; COptions::getValue("Save", Save); CCopasiDataModel::Global->saveModel(Save); // Since only one save file name can be specified we // stop execution. return 0; } // CCopasiDataModel::Global->saveModel(""); } //#endif // XXXX } catch (CCopasiException Exception) { std::cout << Exception.getMessage().getText() << std::endl; } pdelete(CCopasiDataModel::Global); pdelete(CCopasiContainer::Root); //std::cout << "Leaving main program." << std::endl; return 0; } <|endoftext|>
<commit_before>54c75aee-2e3a-11e5-8980-c03896053bdd<commit_msg>54d4f1f4-2e3a-11e5-bf3a-c03896053bdd<commit_after>54d4f1f4-2e3a-11e5-bf3a-c03896053bdd<|endoftext|>
<commit_before>#include <stdlib.h> #include <argp.h> #include <stdio.h> #include <string> #include <iostream> #include "FatSystem.h" #include "FatPath.h" #include "FatChains.h" #include "FatBackup.h" #include "FatDiff.h" using namespace std; void usage() { cout << "fatcat v1.0, Gregwar <g.passault@gmail.com>" << endl; cout << endl; cout << "Usage: fatcat [-i] disk.img" << endl; cout << " -i: display information about disk" << endl; cout << endl; cout << "Browsing & extracting:" << endl; cout << " -l [dir]: list files and directories in the given path" << endl; cout << " -L [cluster]: list files and directories in the given cluster" << endl; cout << " -r [path]: reads the file given by the path" << endl; cout << " -R [cluster]: reads the data from given cluster" << endl; cout << " -s [size]: specify the size of data to read from the cluster" << endl; cout << " -d: enable listing of deleted files" << endl; cout << " -x [directory]: extract all files to a directory, deleted files included if -d" << endl; cout << " -c: enable contiguous mode" << endl; cout << endl; cout << "FAT Hacking" << endl; cout << " -@ [cluster]: Get the cluster address and informations" << endl; cout << " -2: analysis & compare the 2 FATs" << endl; cout << " -b [file]: backup the FATs" << endl; cout << "* -p [file]: restore (patch) the FATs" << endl; cout << "* -w [cluster] -v [value]: write next cluster (see -T)" << endl; cout << " -T [table]: specify which table to write (0:both, 1:first, 2:second)" << endl; cout << "* -m: merge the FATs" << endl; cout << " -k: analysis the chains" << endl; cout << endl; cout << "*: These flags writes on the disk, be careful" << endl; cout << endl; exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { vector<string> arguments; char *image = NULL; int index; // -s, specify the size to be read int size = -1; // -i, display informations about the disk bool infoFlag = false; // -l, list directories in the given path bool listFlag = false; string listPath; // -c, listing for a direct cluster bool listClusterFlag = false; int listCluster; // -r, reads a file bool readFlag = false; string readPath; // -t, reads from cluster file bool clusterRead = false; int cluster; // -d, lists deleted bool listDeleted = false; // -c: contiguous mode bool contiguous = false; // -x: extract bool extract = false; string extractDirectory; // -2: compare two fats bool compare = false; // -@: get the cluster address bool address = false; // -k: analysis the chains bool chains = false; // -b: backup the fats bool backup = false; bool patch = false; string backupFile; // -w: write next cluster bool writeNext = false; // -m: merge the FATs bool merge = false; // -v: value bool hasValue = false; int value; // -T: FAT table to write int table; // Parsing command line while ((index = getopt(argc, argv, "il:L:r:R:s:dchx:2@:kb:p:w:v:mT:")) != -1) { switch (index) { case 'T': table = atoi(optarg); break; case 'm': merge = true; break; case 'v': hasValue = true; value = atoi(optarg); break; case 'w': writeNext = true; cluster = atoi(optarg); break; case '@': address = true; cluster = atoi(optarg); break; case 'k': chains = true; break; case 'i': infoFlag = true; break; case 'l': listFlag = true; listPath = string(optarg); break; case 'L': listClusterFlag = true; listCluster = atoi(optarg); break; case 'r': readFlag = true; readPath = string(optarg); break; case 'R': clusterRead = true; cluster = atoi(optarg); break; case 's': size = atoi(optarg); break; case 'd': listDeleted = true; break; case 'c': contiguous = true; break; case 'x': extract = true; extractDirectory = string(optarg); break; case '2': compare = true; break; case 'b': backup = true; backupFile = string(optarg); break; case 'p': patch = true; backupFile = string(optarg); break; case 'h': usage(); break; } } // Trying to get the FAT file or device if (optind != argc) { image = argv[optind]; } if (!image) { usage(); } // Getting extra arguments for (index=optind+1; index<argc; index++) { arguments.push_back(argv[index]); } // If the user did not required any actions if (!(infoFlag || listFlag || listClusterFlag || readFlag || clusterRead || extract || compare || address || chains || backup || patch || writeNext || merge)) { usage(); } try { // Openning the image FatSystem fat(image); fat.setListDeleted(listDeleted); fat.setContiguous(contiguous); if (fat.init()) { if (infoFlag) { fat.infos(); } else if (listFlag) { cout << "Listing path " << listPath << endl; FatPath path(listPath); fat.list(path); } else if (listClusterFlag) { cout << "Listing cluster " << listCluster << endl; fat.list(listCluster); } else if (readFlag) { FatPath path(readPath); fat.readFile(path); } else if (clusterRead) { fat.readFile(cluster, size); } else if (extract) { fat.extract(extractDirectory); } else if (compare) { FatDiff diff(fat); diff.compare(); } else if (address) { cout << "Cluster " << cluster << " address:" << endl; int addr = fat.clusterAddress(cluster); int next1 = fat.nextCluster(cluster, 0); int next2 = fat.nextCluster(cluster, 1); printf("%d (%08x)\n", addr, addr); cout << "Next cluster:" << endl; printf("FAT1: %u (%08x)\n", next1, next1); printf("FAT2: %u (%08x)\n", next2, next2); } else if (chains) { FatChains chains(fat); chains.findChains(); } else if (backup || patch) { FatBackup backupSystem(fat); if (backup) { backupSystem.backup(backupFile); } else { backupSystem.patch(backupFile); } } else if (writeNext) { if (!hasValue) { throw string("You should provide a value with -v"); } int prev = fat.nextCluster(cluster); printf("Writing next cluster of %u from %u to %u\n", cluster, prev, value); fat.enableWrite(); if (table == 0 || table == 1) { printf("Writing on FAT1\n"); fat.writeNextCluster(cluster, value, 0); } if (table == 0 || table == 2) { printf("Writing on FAT2\n"); fat.writeNextCluster(cluster, value, 1); } } else if (merge) { FatDiff diff(fat); diff.merge(); } } else { cout << "! Failed to init the FAT filesystem" << endl; } fat.enableWrite(); for (int i=0; i<fat.totalClusters/2; i++) { fat.writeNextCluster(i, 0xffffffff, 0); } } catch (string error) { cerr << "Error: " << error << endl; } exit(EXIT_SUCCESS); } <commit_msg>Removing mistake commit<commit_after>#include <stdlib.h> #include <argp.h> #include <stdio.h> #include <string> #include <iostream> #include "FatSystem.h" #include "FatPath.h" #include "FatChains.h" #include "FatBackup.h" #include "FatDiff.h" using namespace std; void usage() { cout << "fatcat v1.0, Gregwar <g.passault@gmail.com>" << endl; cout << endl; cout << "Usage: fatcat [-i] disk.img" << endl; cout << " -i: display information about disk" << endl; cout << endl; cout << "Browsing & extracting:" << endl; cout << " -l [dir]: list files and directories in the given path" << endl; cout << " -L [cluster]: list files and directories in the given cluster" << endl; cout << " -r [path]: reads the file given by the path" << endl; cout << " -R [cluster]: reads the data from given cluster" << endl; cout << " -s [size]: specify the size of data to read from the cluster" << endl; cout << " -d: enable listing of deleted files" << endl; cout << " -x [directory]: extract all files to a directory, deleted files included if -d" << endl; cout << " -c: enable contiguous mode" << endl; cout << endl; cout << "FAT Hacking" << endl; cout << " -@ [cluster]: Get the cluster address and informations" << endl; cout << " -2: analysis & compare the 2 FATs" << endl; cout << " -b [file]: backup the FATs" << endl; cout << "* -p [file]: restore (patch) the FATs" << endl; cout << "* -w [cluster] -v [value]: write next cluster (see -T)" << endl; cout << " -T [table]: specify which table to write (0:both, 1:first, 2:second)" << endl; cout << "* -m: merge the FATs" << endl; cout << " -k: analysis the chains" << endl; cout << endl; cout << "*: These flags writes on the disk, be careful" << endl; cout << endl; exit(EXIT_FAILURE); } int main(int argc, char *argv[]) { vector<string> arguments; char *image = NULL; int index; // -s, specify the size to be read int size = -1; // -i, display informations about the disk bool infoFlag = false; // -l, list directories in the given path bool listFlag = false; string listPath; // -c, listing for a direct cluster bool listClusterFlag = false; int listCluster; // -r, reads a file bool readFlag = false; string readPath; // -t, reads from cluster file bool clusterRead = false; int cluster; // -d, lists deleted bool listDeleted = false; // -c: contiguous mode bool contiguous = false; // -x: extract bool extract = false; string extractDirectory; // -2: compare two fats bool compare = false; // -@: get the cluster address bool address = false; // -k: analysis the chains bool chains = false; // -b: backup the fats bool backup = false; bool patch = false; string backupFile; // -w: write next cluster bool writeNext = false; // -m: merge the FATs bool merge = false; // -v: value bool hasValue = false; int value; // -T: FAT table to write int table; // Parsing command line while ((index = getopt(argc, argv, "il:L:r:R:s:dchx:2@:kb:p:w:v:mT:")) != -1) { switch (index) { case 'T': table = atoi(optarg); break; case 'm': merge = true; break; case 'v': hasValue = true; value = atoi(optarg); break; case 'w': writeNext = true; cluster = atoi(optarg); break; case '@': address = true; cluster = atoi(optarg); break; case 'k': chains = true; break; case 'i': infoFlag = true; break; case 'l': listFlag = true; listPath = string(optarg); break; case 'L': listClusterFlag = true; listCluster = atoi(optarg); break; case 'r': readFlag = true; readPath = string(optarg); break; case 'R': clusterRead = true; cluster = atoi(optarg); break; case 's': size = atoi(optarg); break; case 'd': listDeleted = true; break; case 'c': contiguous = true; break; case 'x': extract = true; extractDirectory = string(optarg); break; case '2': compare = true; break; case 'b': backup = true; backupFile = string(optarg); break; case 'p': patch = true; backupFile = string(optarg); break; case 'h': usage(); break; } } // Trying to get the FAT file or device if (optind != argc) { image = argv[optind]; } if (!image) { usage(); } // Getting extra arguments for (index=optind+1; index<argc; index++) { arguments.push_back(argv[index]); } // If the user did not required any actions if (!(infoFlag || listFlag || listClusterFlag || readFlag || clusterRead || extract || compare || address || chains || backup || patch || writeNext || merge)) { usage(); } try { // Openning the image FatSystem fat(image); fat.setListDeleted(listDeleted); fat.setContiguous(contiguous); if (fat.init()) { if (infoFlag) { fat.infos(); } else if (listFlag) { cout << "Listing path " << listPath << endl; FatPath path(listPath); fat.list(path); } else if (listClusterFlag) { cout << "Listing cluster " << listCluster << endl; fat.list(listCluster); } else if (readFlag) { FatPath path(readPath); fat.readFile(path); } else if (clusterRead) { fat.readFile(cluster, size); } else if (extract) { fat.extract(extractDirectory); } else if (compare) { FatDiff diff(fat); diff.compare(); } else if (address) { cout << "Cluster " << cluster << " address:" << endl; int addr = fat.clusterAddress(cluster); int next1 = fat.nextCluster(cluster, 0); int next2 = fat.nextCluster(cluster, 1); printf("%d (%08x)\n", addr, addr); cout << "Next cluster:" << endl; printf("FAT1: %u (%08x)\n", next1, next1); printf("FAT2: %u (%08x)\n", next2, next2); } else if (chains) { FatChains chains(fat); chains.findChains(); } else if (backup || patch) { FatBackup backupSystem(fat); if (backup) { backupSystem.backup(backupFile); } else { backupSystem.patch(backupFile); } } else if (writeNext) { if (!hasValue) { throw string("You should provide a value with -v"); } int prev = fat.nextCluster(cluster); printf("Writing next cluster of %u from %u to %u\n", cluster, prev, value); fat.enableWrite(); if (table == 0 || table == 1) { printf("Writing on FAT1\n"); fat.writeNextCluster(cluster, value, 0); } if (table == 0 || table == 2) { printf("Writing on FAT2\n"); fat.writeNextCluster(cluster, value, 1); } } else if (merge) { FatDiff diff(fat); diff.merge(); } } else { cout << "! Failed to init the FAT filesystem" << endl; } } catch (string error) { cerr << "Error: " << error << endl; } exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "attribute_reprocessing_initializer.h" #include <vespa/searchcore/proton/attribute/attribute_populator.h> #include <vespa/searchcore/proton/attribute/document_field_populator.h> #include <vespa/searchcore/proton/attribute/filter_attribute_manager.h> #include <vespa/searchcore/proton/common/i_indexschema_inspector.h> #include <vespa/searchlib/attribute/attributevector.h> #include <vespa/log/log.h> LOG_SETUP(".proton.reprocessing.attribute_reprocessing_initializer"); using namespace search::index; using search::AttributeGuard; using search::AttributeVector; using search::SerialNum; using search::index::schema::DataType; using search::attribute::BasicType; namespace proton { typedef AttributeReprocessingInitializer::Config ARIConfig; namespace { constexpr search::SerialNum ATTRIBUTE_INIT_SERIAL = 1; const char * toStr(bool value) { return (value ? "true" : "false"); } bool fastPartialUpdateAttribute(BasicType::Type attrType) { // Partial update to tensor or predicate attribute must update document return ((attrType != BasicType::Type::PREDICATE) && (attrType != BasicType::Type::TENSOR) && (attrType != BasicType::Type::REFERENCE)); } bool isStructFieldAttribute(const vespalib::string &name) { return name.find('.') != vespalib::string::npos; } FilterAttributeManager::AttributeSet getAttributeSetToPopulate(const ARIConfig &newCfg, const ARIConfig &oldCfg, const IDocumentTypeInspector &inspector, search::SerialNum serialNum) { FilterAttributeManager::AttributeSet attrsToPopulate; std::vector<AttributeGuard> attrList; newCfg.getAttrMgr()->getAttributeList(attrList); for (const auto &guard : attrList) { const vespalib::string &name = guard->getName(); bool inOldAttrMgr = oldCfg.getAttrMgr()->getAttribute(name)->valid(); bool unchangedField = inspector.hasUnchangedField(name); search::SerialNum flushedSerialNum = newCfg.getAttrMgr()->getFlushedSerialNum(name); bool populateAttribute = !inOldAttrMgr && unchangedField && (flushedSerialNum < serialNum); LOG(debug, "getAttributeSetToPopulate(): name='%s', inOldAttrMgr=%s, unchangedField=%s, populate=%s", name.c_str(), toStr(inOldAttrMgr), toStr(unchangedField), toStr(populateAttribute)); if (populateAttribute) { attrsToPopulate.insert(name); } } return attrsToPopulate; } IReprocessingReader::SP getAttributesToPopulate(const ARIConfig &newCfg, const ARIConfig &oldCfg, const IDocumentTypeInspector &inspector, const vespalib::string &subDbName, search::SerialNum serialNum) { FilterAttributeManager::AttributeSet attrsToPopulate = getAttributeSetToPopulate(newCfg, oldCfg, inspector, serialNum); if (!attrsToPopulate.empty()) { return IReprocessingReader::SP(new AttributePopulator (IAttributeManager::SP(new FilterAttributeManager (attrsToPopulate, newCfg.getAttrMgr())), ATTRIBUTE_INIT_SERIAL, subDbName, serialNum)); } return IReprocessingReader::SP(); } std::vector<IReprocessingRewriter::SP> getFieldsToPopulate(const ARIConfig &newCfg, const ARIConfig &oldCfg, const IDocumentTypeInspector &inspector, const IIndexschemaInspector &oldIndexschemaInspector, const vespalib::string &subDbName) { std::vector<IReprocessingRewriter::SP> fieldsToPopulate; std::vector<AttributeGuard> attrList; oldCfg.getAttrMgr()->getAttributeList(attrList); for (const auto &guard : attrList) { const vespalib::string &name = guard->getName(); BasicType attrType(guard->getConfig().basicType()); bool inNewAttrMgr = newCfg.getAttrMgr()->getAttribute(name)->valid(); bool unchangedField = inspector.hasUnchangedField(name); // NOTE: If it is a string and index field we shall // keep the original in order to preserve annotations. bool wasStringIndexField = oldIndexschemaInspector.isStringIndex(name); bool populateField = !inNewAttrMgr && unchangedField && !wasStringIndexField && fastPartialUpdateAttribute(attrType.type()) && !isStructFieldAttribute(name); LOG(debug, "getFieldsToPopulate(): name='%s', inNewAttrMgr=%s, unchangedField=%s, " "wasStringIndexField=%s, dataType=%s, populate=%s", name.c_str(), toStr(inNewAttrMgr), toStr(unchangedField), toStr(wasStringIndexField), attrType.asString(), toStr(populateField)); if (populateField) { fieldsToPopulate.push_back(IReprocessingRewriter::SP (new DocumentFieldPopulator(name, guard.getSP(), subDbName))); } } return fieldsToPopulate; } } AttributeReprocessingInitializer:: AttributeReprocessingInitializer(const Config &newCfg, const Config &oldCfg, const IDocumentTypeInspector &inspector, const IIndexschemaInspector &oldIndexschemaInspector, const vespalib::string &subDbName, search::SerialNum serialNum) : _attrsToPopulate(getAttributesToPopulate(newCfg, oldCfg, inspector, subDbName, serialNum)), _fieldsToPopulate(getFieldsToPopulate(newCfg, oldCfg, inspector, oldIndexschemaInspector, subDbName)) { } bool AttributeReprocessingInitializer::hasReprocessors() const { return _attrsToPopulate.get() != nullptr || !_fieldsToPopulate.empty(); } void AttributeReprocessingInitializer::initialize(IReprocessingHandler &handler) { if (_attrsToPopulate.get() != nullptr) { handler.addReader(_attrsToPopulate); } if (!_fieldsToPopulate.empty()) { for (const auto &rewriter : _fieldsToPopulate) { handler.addRewriter(rewriter); } } } } // namespace proton <commit_msg>std::make_shared<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "attribute_reprocessing_initializer.h" #include <vespa/searchcore/proton/attribute/attribute_populator.h> #include <vespa/searchcore/proton/attribute/document_field_populator.h> #include <vespa/searchcore/proton/attribute/filter_attribute_manager.h> #include <vespa/searchcore/proton/common/i_indexschema_inspector.h> #include <vespa/searchlib/attribute/attributevector.h> #include <vespa/log/log.h> LOG_SETUP(".proton.reprocessing.attribute_reprocessing_initializer"); using namespace search::index; using search::AttributeGuard; using search::AttributeVector; using search::SerialNum; using search::index::schema::DataType; using search::attribute::BasicType; namespace proton { typedef AttributeReprocessingInitializer::Config ARIConfig; namespace { constexpr search::SerialNum ATTRIBUTE_INIT_SERIAL = 1; const char * toStr(bool value) { return (value ? "true" : "false"); } bool fastPartialUpdateAttribute(BasicType::Type attrType) { // Partial update to tensor or predicate attribute must update document return ((attrType != BasicType::Type::PREDICATE) && (attrType != BasicType::Type::TENSOR) && (attrType != BasicType::Type::REFERENCE)); } bool isStructFieldAttribute(const vespalib::string &name) { return name.find('.') != vespalib::string::npos; } FilterAttributeManager::AttributeSet getAttributeSetToPopulate(const ARIConfig &newCfg, const ARIConfig &oldCfg, const IDocumentTypeInspector &inspector, search::SerialNum serialNum) { FilterAttributeManager::AttributeSet attrsToPopulate; std::vector<AttributeGuard> attrList; newCfg.getAttrMgr()->getAttributeList(attrList); for (const auto &guard : attrList) { const vespalib::string &name = guard->getName(); bool inOldAttrMgr = oldCfg.getAttrMgr()->getAttribute(name)->valid(); bool unchangedField = inspector.hasUnchangedField(name); search::SerialNum flushedSerialNum = newCfg.getAttrMgr()->getFlushedSerialNum(name); bool populateAttribute = !inOldAttrMgr && unchangedField && (flushedSerialNum < serialNum); LOG(debug, "getAttributeSetToPopulate(): name='%s', inOldAttrMgr=%s, unchangedField=%s, populate=%s", name.c_str(), toStr(inOldAttrMgr), toStr(unchangedField), toStr(populateAttribute)); if (populateAttribute) { attrsToPopulate.insert(name); } } return attrsToPopulate; } IReprocessingReader::SP getAttributesToPopulate(const ARIConfig &newCfg, const ARIConfig &oldCfg, const IDocumentTypeInspector &inspector, const vespalib::string &subDbName, search::SerialNum serialNum) { FilterAttributeManager::AttributeSet attrsToPopulate = getAttributeSetToPopulate(newCfg, oldCfg, inspector, serialNum); if (!attrsToPopulate.empty()) { return std::make_shared<AttributePopulator> (std::make_shared<FilterAttributeManager>(attrsToPopulate, newCfg.getAttrMgr()), ATTRIBUTE_INIT_SERIAL, subDbName, serialNum); } return IReprocessingReader::SP(); } std::vector<IReprocessingRewriter::SP> getFieldsToPopulate(const ARIConfig &newCfg, const ARIConfig &oldCfg, const IDocumentTypeInspector &inspector, const IIndexschemaInspector &oldIndexschemaInspector, const vespalib::string &subDbName) { std::vector<IReprocessingRewriter::SP> fieldsToPopulate; std::vector<AttributeGuard> attrList; oldCfg.getAttrMgr()->getAttributeList(attrList); for (const auto &guard : attrList) { const vespalib::string &name = guard->getName(); BasicType attrType(guard->getConfig().basicType()); bool inNewAttrMgr = newCfg.getAttrMgr()->getAttribute(name)->valid(); bool unchangedField = inspector.hasUnchangedField(name); // NOTE: If it is a string and index field we shall // keep the original in order to preserve annotations. bool wasStringIndexField = oldIndexschemaInspector.isStringIndex(name); bool populateField = !inNewAttrMgr && unchangedField && !wasStringIndexField && fastPartialUpdateAttribute(attrType.type()) && !isStructFieldAttribute(name); LOG(debug, "getFieldsToPopulate(): name='%s', inNewAttrMgr=%s, unchangedField=%s, " "wasStringIndexField=%s, dataType=%s, populate=%s", name.c_str(), toStr(inNewAttrMgr), toStr(unchangedField), toStr(wasStringIndexField), attrType.asString(), toStr(populateField)); if (populateField) { fieldsToPopulate.push_back(IReprocessingRewriter::SP (new DocumentFieldPopulator(name, guard.getSP(), subDbName))); } } return fieldsToPopulate; } } AttributeReprocessingInitializer:: AttributeReprocessingInitializer(const Config &newCfg, const Config &oldCfg, const IDocumentTypeInspector &inspector, const IIndexschemaInspector &oldIndexschemaInspector, const vespalib::string &subDbName, search::SerialNum serialNum) : _attrsToPopulate(getAttributesToPopulate(newCfg, oldCfg, inspector, subDbName, serialNum)), _fieldsToPopulate(getFieldsToPopulate(newCfg, oldCfg, inspector, oldIndexschemaInspector, subDbName)) { } bool AttributeReprocessingInitializer::hasReprocessors() const { return _attrsToPopulate.get() != nullptr || !_fieldsToPopulate.empty(); } void AttributeReprocessingInitializer::initialize(IReprocessingHandler &handler) { if (_attrsToPopulate.get() != nullptr) { handler.addReader(_attrsToPopulate); } if (!_fieldsToPopulate.empty()) { for (const auto &rewriter : _fieldsToPopulate) { handler.addRewriter(rewriter); } } } } // namespace proton <|endoftext|>
<commit_before>/* Original code from tekkies/CVdrone (get actual address from github) Modified by Elliot Greenlee, Caleb Mennen, Jacob Pollack COSC 402 Senior Design Min Kao Drone Tour See readme at (get actual address from github) */ #include "ardrone/ardrone.h" #include "control.h" #include "structures.h" #include <iostream> #include <vector> #include <string> using namespace std; int main(int argc, char *argv[]) { Control *control; int wait = 33; try { //Initialize main control variables and flight modes control = new Control(); } catch (const char *msg) { cout << msg << endl; return -1; } // Setting up for constant time double time_counter = 0; clock_t this_time = clock(); clock_t last_time = this_time; long long executions = 0; // Main loop while (1) { //Time stuff this_time = clock(); time_counter += (double) (this_time - last_time); last_time = this_time; executions++; double time_delay = 1.0 / 25; if (time_counter < (time_delay * CLOCKS_PER_SEC)) { //AKA not enough time has passed continue; } time_counter -= time_delay * CLOCKS_PER_SEC; printf("I hit %lli times\n", executions); executions = 0; // exit(0); //Detect user key input and end loop if ESC is pressed if (!control->getKey(wait)) break; control->detectFlyingMode(); //b, n, m to change mode control->changeSpeed(); //0-9 to change speed control->detectTakeoff(); //spacebar to take off //Get the image from the camera control->getImage(); //Run drone control control->fly(); //Display image overlay values control->overlayControl(); //Send move command to the drone control->move(); } //Close flying modes and drone connection control->close(); return 0; } <commit_msg>restrict main to execute only 25 times a second<commit_after>/* Original code from tekkies/CVdrone (get actual address from github) Modified by Elliot Greenlee, Caleb Mennen, Jacob Pollack COSC 402 Senior Design Min Kao Drone Tour See readme at (get actual address from github) */ #include "ardrone/ardrone.h" #include "control.h" #include "structures.h" #include <iostream> #include <vector> #include <string> using namespace std; int main(int argc, char *argv[]) { Control *control; int wait = 33; try { //Initialize main control variables and flight modes control = new Control(); } catch (const char *msg) { cout << msg << endl; return -1; } // Setting up for constant time double time_counter = 0; clock_t this_time = clock(); clock_t last_time = this_time; long long executions = 0; // Main loop while (1) { //Time stuff this_time = clock(); time_counter += (double) (this_time - last_time); last_time = this_time; executions++; double time_delay = 1.0 / 25; if (time_counter < (time_delay * CLOCKS_PER_SEC)) { //AKA not enough time has passed continue; } time_counter -= time_delay * CLOCKS_PER_SEC; // printf("I hit %lli times\n", executions); executions = 0; // exit(0); //Detect user key input and end loop if ESC is pressed if (!control->getKey(wait)) break; control->detectFlyingMode(); //b, n, m to change mode control->changeSpeed(); //0-9 to change speed control->detectTakeoff(); //spacebar to take off //Get the image from the camera control->getImage(); //Run drone control control->fly(); //Display image overlay values control->overlayControl(); //Send move command to the drone control->move(); } //Close flying modes and drone connection control->close(); return 0; } <|endoftext|>
<commit_before>20bcc1b6-2f67-11e5-972a-6c40088e03e4<commit_msg>20c39c40-2f67-11e5-8783-6c40088e03e4<commit_after>20c39c40-2f67-11e5-8783-6c40088e03e4<|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #include "precomp.hpp" #include "opencv2/hal/intrin.hpp" namespace cv { void spatialGradient( InputArray _src, OutputArray _dx, OutputArray _dy, int ksize ) { // Prepare InputArray src Mat src = _src.getMat(); CV_Assert( !src.empty() ); CV_Assert( src.isContinuous() ); CV_Assert( src.type() == CV_8UC1 ); // Prepare OutputArrays dx, dy _dx.create( src.size(), CV_16SC1 ); _dy.create( src.size(), CV_16SC1 ); Mat dx = _dx.getMat(), dy = _dy.getMat(); CV_Assert( dx.isContinuous() ); CV_Assert( dy.isContinuous() ); // TODO: Allow for other kernel sizes CV_Assert(ksize == 3); // Reference //Sobel( src, dx, CV_16SC1, 1, 0, ksize ); //Sobel( src, dy, CV_16SC1, 0, 1, ksize ); // Get dimensions int H = src.rows, W = src.cols, N = H * W; // Get raw pointers to input/output data uchar* p_src = src.ptr<uchar>(0); short* p_dx = dx.ptr<short>(0); short* p_dy = dy.ptr<short>(0); // Row, column indices int i, j; /* NOTE: * * Sobel-x: -1 0 1 * -2 0 2 * -1 0 1 * * Sobel-y: -1 -2 -1 * 0 0 0 * 1 2 1 */ // No-SSE int idx; p_dx[0] = 0; // Top-left corner p_dy[0] = 0; p_dx[W-1] = 0; // Top-right corner p_dy[W-1] = 0; p_dx[N-1] = 0; // Bottom-right corner p_dy[N-1] = 0; p_dx[N-W] = 0; // Bottom-left corner p_dy[N-W] = 0; // Handle special case: column matrix if ( W == 1 ) { for ( i = 1; i < H - 1; i++ ) { p_dx[i] = 0; p_dy[i] = 4*(p_src[i + 1] - p_src[i - 1]); // Should be 2?! 4 makes tests pass } return; } // Handle special case: row matrix if ( H == 1 ) { for ( j = 1; j < W - 1; j++ ) { p_dx[j] = 4*(p_src[j + 1] - p_src[j - 1]); // Should be 2?! 4 makes tests pass p_dy[j] = 0; } return; } // Do top row for ( j = 1; j < W - 1; j++ ) { idx = j; p_dx[idx] = -(p_src[idx+W-1] + 2*p_src[idx-1] + p_src[idx+W-1]) + (p_src[idx+W+1] + 2*p_src[idx+1] + p_src[idx+W+1]); p_dy[idx] = 0; } // Do right column idx = 2*W - 1; for ( i = 1; i < H - 1; i++ ) { p_dx[idx] = 0; p_dy[idx] = -(p_src[idx-W-1] + 2*p_src[idx-W] + p_src[idx-W-1]) + (p_src[idx+W-1] + 2*p_src[idx+W] + p_src[idx+W-1]); idx += W; } // Do bottom row idx = N - W + 1; for ( j = 1; j < W - 1; j++ ) { p_dx[idx] = -(p_src[idx-W-1] + 2*p_src[idx-1] + p_src[idx-W-1]) + (p_src[idx-W+1] + 2*p_src[idx+1] + p_src[idx-W+1]); p_dy[idx] = 0; idx++; } // Do left column idx = W; for ( i = 1; i < H - 1; i++ ) { p_dx[idx] = 0; p_dy[idx] = -(p_src[idx-W+1] + 2*p_src[idx-W] + p_src[idx-W+1]) + (p_src[idx+W+1] + 2*p_src[idx+W] + p_src[idx+W+1]); idx += W; } // Do Inner area #if CV_SIMD128 // Characters in variable names have the following meanings: // u: unsigned char // s: signed int // // [row][column] // m: offset -1 // n: offset 0 // p: offset 1 // Example: umn is offset -1 in row and offset 0 in column v_uint8x16 v_umm, v_umn, v_ump, v_unm, v_unn, v_unp, v_upm, v_upn, v_upp; v_uint16x8 v_umm1, v_umm2, v_umn1, v_umn2, v_ump1, v_ump2, v_unm1, v_unm2, v_unn1, v_unn2, v_unp1, v_unp2, v_upm1, v_upm2, v_upn1, v_upn2, v_upp1, v_upp2; v_int16x8 v_smm1, v_smm2, v_smn1, v_smn2, v_smp1, v_smp2, v_snm1, v_snm2, v_snn1, v_snn2, v_snp1, v_snp2, v_spm1, v_spm2, v_spn1, v_spn2, v_spp1, v_spp2, v_two = v_setall_s16(2), v_sdx1, v_sdx2, v_sdy1, v_sdy2; for ( i = 1; i < H - 1; i++ ) for ( j = 1; j < W - 1 - 15; j += 16 ) { // Load idx = i*W + j; v_umm = v_load(&p_src[idx - W - 1]); v_umn = v_load(&p_src[idx - W]); v_ump = v_load(&p_src[idx - W + 1]); v_unm = v_load(&p_src[idx - 1]); v_unn = v_load(&p_src[idx]); v_unp = v_load(&p_src[idx + 1]); v_upm = v_load(&p_src[idx + W - 1]); v_upn = v_load(&p_src[idx + W]); v_upp = v_load(&p_src[idx + W + 1]); // Expand to uint v_expand(v_umm, v_umm1, v_umm2); v_expand(v_umn, v_umn1, v_umn2); v_expand(v_ump, v_ump1, v_ump2); v_expand(v_unm, v_unm1, v_unm2); v_expand(v_unn, v_unn1, v_unn2); v_expand(v_unp, v_unp1, v_unp2); v_expand(v_upm, v_upm1, v_upm2); v_expand(v_upn, v_upn1, v_upn2); v_expand(v_upp, v_upp1, v_upp2); // Convert to int v_smm1 = v_reinterpret_as_s16(v_umm1); v_smm2 = v_reinterpret_as_s16(v_umm2); v_smn1 = v_reinterpret_as_s16(v_umn1); v_smn2 = v_reinterpret_as_s16(v_umn2); v_smp1 = v_reinterpret_as_s16(v_ump1); v_smp2 = v_reinterpret_as_s16(v_ump2); v_snm1 = v_reinterpret_as_s16(v_unm1); v_snm2 = v_reinterpret_as_s16(v_unm2); v_snn1 = v_reinterpret_as_s16(v_unn1); v_snn2 = v_reinterpret_as_s16(v_unn2); v_snp1 = v_reinterpret_as_s16(v_unp1); v_snp2 = v_reinterpret_as_s16(v_unp2); v_spm1 = v_reinterpret_as_s16(v_upm1); v_spm2 = v_reinterpret_as_s16(v_upm2); v_spn1 = v_reinterpret_as_s16(v_upn1); v_spn2 = v_reinterpret_as_s16(v_upn2); v_spp1 = v_reinterpret_as_s16(v_upp1); v_spp2 = v_reinterpret_as_s16(v_upp2); // dx v_sdx1 = (v_smp1 - v_smm1) + v_two*(v_snp1 - v_snm1) + (v_spp1 - v_spm1); v_sdx2 = (v_smp2 - v_smm2) + v_two*(v_snp2 - v_snm2) + (v_spp2 - v_spm2); // dy v_sdy1 = (v_spm1 - v_smm1) + v_two*(v_spn1 - v_smn1) + (v_spp1 - v_smp1); v_sdy2 = (v_spm2 - v_smm2) + v_two*(v_spn2 - v_smn2) + (v_spp2 - v_smp2); // Store v_store(&p_dx[idx], v_sdx1); v_store(&p_dx[idx+8], v_sdx2); v_store(&p_dy[idx], v_sdy1); v_store(&p_dy[idx+8], v_sdy2); } // Cleanup int end_j = j; for ( i = 1; i < H - 1; i++ ) for ( j = end_j; j < W - 1; j++ ) { idx = i*W + j; p_dx[idx] = -(p_src[idx-W-1] + 2*p_src[idx-1] + p_src[idx+W-1]) + (p_src[idx-W+1] + 2*p_src[idx+1] + p_src[idx+W+1]); p_dy[idx] = -(p_src[idx-W-1] + 2*p_src[idx-W] + p_src[idx-W+1]) + (p_src[idx+W-1] + 2*p_src[idx+W] + p_src[idx+W+1]); } #else for ( i = 1; i < H - 1; i++ ) for ( j = 1; j < W - 1; j++ ) { idx = i*W + j; p_dx[idx] = -(p_src[idx-W-1] + 2*p_src[idx-1] + p_src[idx+W-1]) + (p_src[idx-W+1] + 2*p_src[idx+1] + p_src[idx+W+1]); p_dy[idx] = -(p_src[idx-W-1] + 2*p_src[idx-W] + p_src[idx-W+1]) + (p_src[idx+W-1] + 2*p_src[idx+W] + p_src[idx+W+1]); } #endif } } <commit_msg>spatialGradient: Less vector loads<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #include "precomp.hpp" #include "opencv2/hal/intrin.hpp" namespace cv { void spatialGradient( InputArray _src, OutputArray _dx, OutputArray _dy, int ksize ) { // Prepare InputArray src Mat src = _src.getMat(); CV_Assert( !src.empty() ); CV_Assert( src.isContinuous() ); CV_Assert( src.type() == CV_8UC1 ); // Prepare OutputArrays dx, dy _dx.create( src.size(), CV_16SC1 ); _dy.create( src.size(), CV_16SC1 ); Mat dx = _dx.getMat(), dy = _dy.getMat(); CV_Assert( dx.isContinuous() ); CV_Assert( dy.isContinuous() ); // TODO: Allow for other kernel sizes CV_Assert(ksize == 3); // Reference //Sobel( src, dx, CV_16SC1, 1, 0, ksize ); //Sobel( src, dy, CV_16SC1, 0, 1, ksize ); // Get dimensions int H = src.rows, W = src.cols, N = H * W; // Get raw pointers to input/output data uchar* p_src = src.ptr<uchar>(0); short* p_dx = dx.ptr<short>(0); short* p_dy = dy.ptr<short>(0); // Row, column indices int i, j; /* NOTE: * * Sobel-x: -1 0 1 * -2 0 2 * -1 0 1 * * Sobel-y: -1 -2 -1 * 0 0 0 * 1 2 1 */ // No-SSE int idx; p_dx[0] = 0; // Top-left corner p_dy[0] = 0; p_dx[W-1] = 0; // Top-right corner p_dy[W-1] = 0; p_dx[N-1] = 0; // Bottom-right corner p_dy[N-1] = 0; p_dx[N-W] = 0; // Bottom-left corner p_dy[N-W] = 0; // Handle special case: column matrix if ( W == 1 ) { for ( i = 1; i < H - 1; i++ ) { p_dx[i] = 0; p_dy[i] = 4*(p_src[i + 1] - p_src[i - 1]); // Should be 2?! 4 makes tests pass } return; } // Handle special case: row matrix if ( H == 1 ) { for ( j = 1; j < W - 1; j++ ) { p_dx[j] = 4*(p_src[j + 1] - p_src[j - 1]); // Should be 2?! 4 makes tests pass p_dy[j] = 0; } return; } // Do top row for ( j = 1; j < W - 1; j++ ) { idx = j; p_dx[idx] = -(p_src[idx+W-1] + 2*p_src[idx-1] + p_src[idx+W-1]) + (p_src[idx+W+1] + 2*p_src[idx+1] + p_src[idx+W+1]); p_dy[idx] = 0; } // Do right column idx = 2*W - 1; for ( i = 1; i < H - 1; i++ ) { p_dx[idx] = 0; p_dy[idx] = -(p_src[idx-W-1] + 2*p_src[idx-W] + p_src[idx-W-1]) + (p_src[idx+W-1] + 2*p_src[idx+W] + p_src[idx+W-1]); idx += W; } // Do bottom row idx = N - W + 1; for ( j = 1; j < W - 1; j++ ) { p_dx[idx] = -(p_src[idx-W-1] + 2*p_src[idx-1] + p_src[idx-W-1]) + (p_src[idx-W+1] + 2*p_src[idx+1] + p_src[idx-W+1]); p_dy[idx] = 0; idx++; } // Do left column idx = W; for ( i = 1; i < H - 1; i++ ) { p_dx[idx] = 0; p_dy[idx] = -(p_src[idx-W+1] + 2*p_src[idx-W] + p_src[idx-W+1]) + (p_src[idx+W+1] + 2*p_src[idx+W] + p_src[idx+W+1]); idx += W; } // Do Inner area #if CV_SIMD128 // Characters in variable names have the following meanings: // u: unsigned char // s: signed int // // [row][column] // m: offset -1 // n: offset 0 // p: offset 1 // Example: umn is offset -1 in row and offset 0 in column v_uint8x16 v_umm, v_umn, v_ump, v_unm, v_unn, v_unp, v_upm, v_upn, v_upp; v_uint16x8 v_umm1, v_umm2, v_umn1, v_umn2, v_ump1, v_ump2, v_unm1, v_unm2, v_unn1, v_unn2, v_unp1, v_unp2, v_upm1, v_upm2, v_upn1, v_upn2, v_upp1, v_upp2; v_int16x8 v_smm1, v_smm2, v_smn1, v_smn2, v_smp1, v_smp2, v_snm1, v_snm2, v_snn1, v_snn2, v_snp1, v_snp2, v_spm1, v_spm2, v_spn1, v_spn2, v_spp1, v_spp2, v_two = v_setall_s16(2), v_sdx1, v_sdx2, v_sdy1, v_sdy2; // Go through 16-column chunks at a time for ( j = 1; j < W - 1 - 15; j += 16 ) { // Load top two rows for 3x3 Sobel filter idx = W + j; v_umm = v_load(&p_src[idx - W - 1]); v_umn = v_load(&p_src[idx - W]); v_ump = v_load(&p_src[idx - W + 1]); v_unm = v_load(&p_src[idx - 1]); v_unn = v_load(&p_src[idx]); v_unp = v_load(&p_src[idx + 1]); // Expand to uint v_expand(v_umm, v_umm1, v_umm2); v_expand(v_umn, v_umn1, v_umn2); v_expand(v_ump, v_ump1, v_ump2); v_expand(v_unm, v_unm1, v_unm2); v_expand(v_unn, v_unn1, v_unn2); v_expand(v_unp, v_unp1, v_unp2); // Convert to int v_smm1 = v_reinterpret_as_s16(v_umm1); v_smm2 = v_reinterpret_as_s16(v_umm2); v_smn1 = v_reinterpret_as_s16(v_umn1); v_smn2 = v_reinterpret_as_s16(v_umn2); v_smp1 = v_reinterpret_as_s16(v_ump1); v_smp2 = v_reinterpret_as_s16(v_ump2); v_snm1 = v_reinterpret_as_s16(v_unm1); v_snm2 = v_reinterpret_as_s16(v_unm2); v_snn1 = v_reinterpret_as_s16(v_unn1); v_snn2 = v_reinterpret_as_s16(v_unn2); v_snp1 = v_reinterpret_as_s16(v_unp1); v_snp2 = v_reinterpret_as_s16(v_unp2); for ( i = 1; i < H - 1; i++ ) { // Load last row for 3x3 Sobel filter idx = i*W + j; v_upm = v_load(&p_src[idx + W - 1]); v_upn = v_load(&p_src[idx + W]); v_upp = v_load(&p_src[idx + W + 1]); // Expand to uint v_expand(v_upm, v_upm1, v_upm2); v_expand(v_upn, v_upn1, v_upn2); v_expand(v_upp, v_upp1, v_upp2); // Convert to int v_spm1 = v_reinterpret_as_s16(v_upm1); v_spm2 = v_reinterpret_as_s16(v_upm2); v_spn1 = v_reinterpret_as_s16(v_upn1); v_spn2 = v_reinterpret_as_s16(v_upn2); v_spp1 = v_reinterpret_as_s16(v_upp1); v_spp2 = v_reinterpret_as_s16(v_upp2); // dx v_sdx1 = (v_smp1 - v_smm1) + v_two*(v_snp1 - v_snm1) + (v_spp1 - v_spm1); v_sdx2 = (v_smp2 - v_smm2) + v_two*(v_snp2 - v_snm2) + (v_spp2 - v_spm2); // dy v_sdy1 = (v_spm1 - v_smm1) + v_two*(v_spn1 - v_smn1) + (v_spp1 - v_smp1); v_sdy2 = (v_spm2 - v_smm2) + v_two*(v_spn2 - v_smn2) + (v_spp2 - v_smp2); // Store v_store(&p_dx[idx], v_sdx1); v_store(&p_dx[idx+8], v_sdx2); v_store(&p_dy[idx], v_sdy1); v_store(&p_dy[idx+8], v_sdy2); // Shift loaded rows up one v_smm1 = v_snm1; v_smm2 = v_snm2; v_smn1 = v_snn1; v_smn2 = v_snn2; v_smp1 = v_snp1; v_smp2 = v_snp2; v_snm1 = v_spm1; v_snm2 = v_spm2; v_snn1 = v_spn1; v_snn2 = v_spn2; v_snp1 = v_spp1; v_snp2 = v_spp2; } } // Cleanup int end_j = j; for ( i = 1; i < H - 1; i++ ) for ( j = end_j; j < W - 1; j++ ) { idx = i*W + j; p_dx[idx] = -(p_src[idx-W-1] + 2*p_src[idx-1] + p_src[idx+W-1]) + (p_src[idx-W+1] + 2*p_src[idx+1] + p_src[idx+W+1]); p_dy[idx] = -(p_src[idx-W-1] + 2*p_src[idx-W] + p_src[idx-W+1]) + (p_src[idx+W-1] + 2*p_src[idx+W] + p_src[idx+W+1]); } #else for ( i = 1; i < H - 1; i++ ) for ( j = 1; j < W - 1; j++ ) { idx = i*W + j; p_dx[idx] = -(p_src[idx-W-1] + 2*p_src[idx-1] + p_src[idx+W-1]) + (p_src[idx-W+1] + 2*p_src[idx+1] + p_src[idx+W+1]); p_dy[idx] = -(p_src[idx-W-1] + 2*p_src[idx-W] + p_src[idx-W+1]) + (p_src[idx+W-1] + 2*p_src[idx+W] + p_src[idx+W+1]); } #endif } } <|endoftext|>
<commit_before>81cf0df7-2d15-11e5-af21-0401358ea401<commit_msg>81cf0df8-2d15-11e5-af21-0401358ea401<commit_after>81cf0df8-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // Main //============================================================================== #include "checkforupdateswindow.h" #include "cliutils.h" #include "coresettings.h" #include "guiutils.h" #include "mainwindow.h" #include "settings.h" #include "splashscreenwindow.h" //============================================================================== #include <QDir> #include <QLocale> #include <QProcess> #include <QSettings> #include <QVariant> #ifdef Q_OS_WIN #include <QWebSettings> #endif //============================================================================== #include <QtSingleApplication> //============================================================================== int main(int pArgC, char *pArgV[]) { // Initialise Qt's message pattern OpenCOR::initQtMessagePattern(); // Determine whether we should try the CLI version of OpenCOR: // - Windows: we never try the CLI version of OpenCOR. We go straight for // its GUI version. // - Linux: we always try the CLI version of OpenCOR and then go for its // GUI version, if needed. // - OS X: we try the CLI version of OpenCOR unless the user double clicks // on the OpenCOR bundle or opens it from the command line by // entering something like: // open OpenCOR.app // in which case we go for its GUI version. // Note #1: on Windows, we have two binaries (.com and .exe that are for the // CLI and GUI versions of OpenCOR, respectively). This means that // when a console window is open, to enter something like: // C:\>OpenCOR // will effectively call OpenCOR.com. From there, should there be // no argument that requires CLI treatment, then the GUI version of // OpenCOR will be run. This is, unfortunately, the only way to // have OpenCOR to behave as both a CLI and a GUI application on // Windows, hence the [OpenCOR]/windows/main.cpp file, which is // used to generate the CLI version of OpenCOR... // Note #2: on OS X, if we were to try to open the OpenCOR bundle from the // command line, then we would get an error message similar to: // LSOpenURLsWithRole() failed with error -10810 for the file [SomePath]/OpenCOR.app. // Fortunately, when double clicking on the OpenCOR bundle or // opening it from the command line, a special argument in the form // of -psn_0_1234567 is passed to OpenCOR, so we can use that to // determine whether we need to force OpenCOR to be run in GUI mode // or whether we first try the CLI version of OpenCOR, and then its // GUI version, if needed... #if defined(Q_OS_WIN) bool tryCliVersion = false; #elif defined(Q_OS_LINUX) bool tryCliVersion = true; #elif defined(Q_OS_MAC) bool tryCliVersion = (pArgC == 1) || memcmp(pArgV[1], "-psn_", 5); #else #error Unsupported platform #endif // Run the CLI version of OpenCOR, if possible/needed if (tryCliVersion) { // Initialise the plugins path OpenCOR::initPluginsPath(pArgV[0]); // Create and initialise the CLI version of OpenCOR QCoreApplication *cliApp = new QCoreApplication(pArgC, pArgV); OpenCOR::initApplication(cliApp); // Try to run the CLI version of OpenCOR int res; bool runCliApplication = OpenCOR::cliApplication(cliApp, &res); OpenCOR::removeGlobalInstances(); delete cliApp; if (runCliApplication) // OpenCOR was run as a CLI application, so leave return res; // Note: at this stage, we tried the CLI version of OpenCOR, but in the // end we need to go for its GUI version, so start over but with // the GUI version of OpenCOR this time... } // Make sure that we always use indirect rendering on Linux // Note: indeed, depending on which plugins are selected, OpenCOR may need // LLVM. If that's the case, and in case the user's video card uses a // driver that relies on LLVM (e.g. Gallium3D and Mesa 3D), then there // may be a conflict between the version of LLVM used by OpenCOR and // the one used by the video card. One way to address this issue is by // using indirect rendering... #ifdef Q_OS_LINUX qputenv("LIBGL_ALWAYS_INDIRECT", "1"); #endif // Initialise the plugins path OpenCOR::initPluginsPath(pArgV[0]); // Create the GUI version of OpenCOR SharedTools::QtSingleApplication *guiApp = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(), pArgC, pArgV); // Send a message (containing the arguments that were passed to this // instance of OpenCOR minus the first one since it corresponds to the full // path to our executable, which we are not interested in) to our 'official' // instance of OpenCOR, should there be one. If there is none, then just // carry on as normal, otherwise exit since we want only one instance of // OpenCOR at any given time QStringList appArguments = guiApp->arguments(); appArguments.removeFirst(); QString arguments = appArguments.join("|"); if (guiApp->isRunning()) { guiApp->sendMessage(arguments); delete guiApp; return 0; } // Initialise the GUI version of OpenCOR QString appDate = QString(); OpenCOR::initApplication(guiApp, &appDate); // Check whether we want to check for new versions at startup QSettings settings(OpenCOR::SettingsOrganization, OpenCOR::SettingsApplication); #ifndef QT_DEBUG settings.beginGroup("CheckForUpdatesWindow"); bool checkForUpdatesAtStartup = settings.value(OpenCOR::SettingsCheckForUpdatesAtStartup, true).toBool(); bool includeSnapshots = settings.value(OpenCOR::SettingsIncludeSnapshots, false).toBool(); settings.endGroup(); #endif // Check whether a new version of OpenCOR is available #ifndef QT_DEBUG if (checkForUpdatesAtStartup) { OpenCOR::CheckForUpdatesEngine *checkForUpdatesEngine = new OpenCOR::CheckForUpdatesEngine(appDate); checkForUpdatesEngine->check(); if ( ( includeSnapshots && checkForUpdatesEngine->hasNewerVersion()) || (!includeSnapshots && checkForUpdatesEngine->hasNewerOfficialVersion())) { // Retrieve the language to be used to show the check for updates // window const QString systemLocale = QLocale::system().name().left(2); QString locale = settings.value(OpenCOR::SettingsLocale, QString()).toString(); if (locale.isEmpty()) locale = systemLocale; QLocale::setDefault(QLocale(locale)); QTranslator qtTranslator; QTranslator appTranslator; qtTranslator.load(":qt_"+locale); qApp->installTranslator(&qtTranslator); appTranslator.load(":app_"+locale); qApp->installTranslator(&appTranslator); // Show the check for updates window // Note: checkForUpdatesEngine gets deleted by // checkForUpdatesWindow... OpenCOR::CheckForUpdatesWindow checkForUpdatesWindow(checkForUpdatesEngine); settings.beginGroup(checkForUpdatesWindow.objectName()); checkForUpdatesWindow.loadSettings(&settings); settings.endGroup(); checkForUpdatesWindow.exec(); settings.beginGroup(checkForUpdatesWindow.objectName()); checkForUpdatesWindow.saveSettings(&settings); settings.endGroup(); } else { delete checkForUpdatesEngine; } } #endif // Initialise our colours by 'updating' them OpenCOR::updateColors(); // Create and show our splash screen, if we are not in debug mode #ifndef QT_DEBUG OpenCOR::SplashScreenWindow *splashScreen = new OpenCOR::SplashScreenWindow(); splashScreen->show(); #endif // Create our main window OpenCOR::MainWindow *win = new OpenCOR::MainWindow(guiApp, appDate); // Keep track of our main window (required by QtSingleApplication so that it // can do what it's supposed to be doing) guiApp->setActivationWindow(win); // Handle our arguments win->handleArguments(arguments); // Show our main window win->show(); // By default, we can and should execute our application bool canExecuteAplication = true; // Close and delete our splash screen once our main window is visible, if we // are not in debug mode #ifndef QT_DEBUG splashScreen->closeAndDeleteAfter(win); // Make sure that our main window is in the foreground, unless the user // decided to close our main window while we were showing our splash screen // Note: indeed, on Linux, to show our splash screen may result in our main // window being shown in the background... if (!win->shuttingDown()) win->showSelf(); else canExecuteAplication = false; #endif // Execute our application, if possible int res; if (canExecuteAplication) res = guiApp->exec(); else res = 0; // Keep track of our application file and directory paths (in case we need // to restart OpenCOR) QString appFilePath = guiApp->applicationFilePath(); QString appDirPath = guiApp->applicationDirPath(); // Delete our main window delete win; // We use QtWebKit, and QWebPage in particular, which results in some leak // messages being generated on Windows when leaving OpenCOR. This is because // an object cache is shared between all QWebPage instances. So to destroy a // QWebPage instance doesn't clear the cache, hence the leak messages. // However, those messages are 'only' warnings, so we can safely live with // them. Still, it doesn't look 'good', so we clear the memory caches, thus // avoiding those leak messages... // Note: the below must absolutely be done after calling guiApp->exec() and // before deleting guiApp... #ifdef Q_OS_WIN QWebSettings::clearMemoryCaches(); #endif // Remove all 'global' instances that were created and used during this // session OpenCOR::removeGlobalInstances(); // Delete our application delete guiApp; // We are done with the execution of our application, so now the question is // whether we need to restart // Note: we do this here rather than 'within' the GUI because once we have // launched a new instance of OpenCOR, we want this instance of // OpenCOR to finish as soon as possible, which will be the case here // since all that remains to be done is to return the result of the // execution of our application... if ((res == OpenCOR::CleanRestart) || (res == OpenCOR::NormalRestart)) { // We want to restart, so the question is whether we want a normal // restart or a clean one if (res == OpenCOR::CleanRestart) // We want a clean restart, so clear all the user settings (indeed, // this will ensure that the various windows are, for instance, // properly reset with regards to their dimensions) settings.clear(); // Restart OpenCOR, but without providing any of the arguments that were // originally passed to us since we want to reset everything QProcess::startDetached(appFilePath, QStringList(), appDirPath); } // We are done running the GUI version of OpenCOR, so leave return res; } //============================================================================== // End of file //============================================================================== <commit_msg>Some minor cleaning up [ci skip].<commit_after>/******************************************************************************* Licensed to the OpenCOR team under one or more contributor license agreements. See the NOTICE.txt file distributed with this work for additional information regarding copyright ownership. The OpenCOR team licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *******************************************************************************/ //============================================================================== // Main //============================================================================== #include "checkforupdateswindow.h" #include "cliutils.h" #include "coresettings.h" #include "guiutils.h" #include "mainwindow.h" #include "settings.h" #include "splashscreenwindow.h" //============================================================================== #include <QDir> #include <QLocale> #include <QProcess> #include <QSettings> #include <QVariant> #ifdef Q_OS_WIN #include <QWebSettings> #endif //============================================================================== #include <QtSingleApplication> //============================================================================== int main(int pArgC, char *pArgV[]) { // Initialise Qt's message pattern OpenCOR::initQtMessagePattern(); // Determine whether we should try the CLI version of OpenCOR: // - Windows: we never try the CLI version of OpenCOR. We go straight for // its GUI version. // - Linux: we always try the CLI version of OpenCOR and then go for its // GUI version, if needed. // - OS X: we try the CLI version of OpenCOR unless the user double clicks // on the OpenCOR bundle or opens it from the command line by // entering something like: // open OpenCOR.app // in which case we go for its GUI version. // Note #1: on Windows, we have two binaries (.com and .exe that are for the // CLI and GUI versions of OpenCOR, respectively). This means that // when a console window is open, to enter something like: // C:\>OpenCOR // will effectively call OpenCOR.com. From there, should there be // no argument that requires CLI treatment, then the GUI version of // OpenCOR will be run. This is, unfortunately, the only way to // have OpenCOR to behave as both a CLI and a GUI application on // Windows, hence the [OpenCOR]/windows/main.cpp file, which is // used to generate the CLI version of OpenCOR... // Note #2: on OS X, if we were to try to open the OpenCOR bundle from the // command line, then we would get an error message similar to: // LSOpenURLsWithRole() failed with error -10810 for the file [SomePath]/OpenCOR.app. // Fortunately, when double clicking on the OpenCOR bundle or // opening it from the command line, a special argument in the form // of -psn_0_1234567 is passed to OpenCOR, so we can use that to // determine whether we need to force OpenCOR to be run in GUI mode // or whether we first try the CLI version of OpenCOR, and then its // GUI version, if needed... #if defined(Q_OS_WIN) bool tryCliVersion = false; #elif defined(Q_OS_LINUX) bool tryCliVersion = true; #elif defined(Q_OS_MAC) bool tryCliVersion = (pArgC == 1) || memcmp(pArgV[1], "-psn_", 5); #else #error Unsupported platform #endif // Run the CLI version of OpenCOR, if possible/needed if (tryCliVersion) { // Initialise the plugins path OpenCOR::initPluginsPath(pArgV[0]); // Create and initialise the CLI version of OpenCOR QCoreApplication *cliApp = new QCoreApplication(pArgC, pArgV); OpenCOR::initApplication(cliApp); // Try to run the CLI version of OpenCOR int res; bool runCliApplication = OpenCOR::cliApplication(cliApp, &res); OpenCOR::removeGlobalInstances(); delete cliApp; if (runCliApplication) // OpenCOR was run as a CLI application, so leave return res; // Note: at this stage, we tried the CLI version of OpenCOR, but in the // end we need to go for its GUI version, so start over but with // the GUI version of OpenCOR this time... } // Make sure that we always use indirect rendering on Linux // Note: indeed, depending on which plugins are selected, OpenCOR may need // LLVM. If that's the case, and in case the user's video card uses a // driver that relies on LLVM (e.g. Gallium3D and Mesa 3D), then there // may be a conflict between the version of LLVM used by OpenCOR and // the one used by the video card. One way to address this issue is by // using indirect rendering... #ifdef Q_OS_LINUX qputenv("LIBGL_ALWAYS_INDIRECT", "1"); #endif // Initialise the plugins path OpenCOR::initPluginsPath(pArgV[0]); // Create the GUI version of OpenCOR SharedTools::QtSingleApplication *guiApp = new SharedTools::QtSingleApplication(QFileInfo(pArgV[0]).baseName(), pArgC, pArgV); // Send a message (containing the arguments that were passed to this // instance of OpenCOR minus the first one since it corresponds to the full // path to our executable, which we are not interested in) to our 'official' // instance of OpenCOR, should there be one. If there is none, then just // carry on as normal, otherwise exit since we want only one instance of // OpenCOR at any given time QStringList appArguments = guiApp->arguments(); appArguments.removeFirst(); QString arguments = appArguments.join("|"); if (guiApp->isRunning()) { guiApp->sendMessage(arguments); delete guiApp; return 0; } // Initialise the GUI version of OpenCOR QString appDate = QString(); OpenCOR::initApplication(guiApp, &appDate); // Check whether we want to check for new versions at startup and, if so, // whether a new version of OpenCOR is available QSettings settings(OpenCOR::SettingsOrganization, OpenCOR::SettingsApplication); #ifndef QT_DEBUG settings.beginGroup("CheckForUpdatesWindow"); bool checkForUpdatesAtStartup = settings.value(OpenCOR::SettingsCheckForUpdatesAtStartup, true).toBool(); bool includeSnapshots = settings.value(OpenCOR::SettingsIncludeSnapshots, false).toBool(); settings.endGroup(); if (checkForUpdatesAtStartup) { OpenCOR::CheckForUpdatesEngine *checkForUpdatesEngine = new OpenCOR::CheckForUpdatesEngine(appDate); checkForUpdatesEngine->check(); if ( ( includeSnapshots && checkForUpdatesEngine->hasNewerVersion()) || (!includeSnapshots && checkForUpdatesEngine->hasNewerOfficialVersion())) { // Retrieve the language to be used to show the check for updates // window const QString systemLocale = QLocale::system().name().left(2); QString locale = settings.value(OpenCOR::SettingsLocale, QString()).toString(); if (locale.isEmpty()) locale = systemLocale; QLocale::setDefault(QLocale(locale)); QTranslator qtTranslator; QTranslator appTranslator; qtTranslator.load(":qt_"+locale); qApp->installTranslator(&qtTranslator); appTranslator.load(":app_"+locale); qApp->installTranslator(&appTranslator); // Show the check for updates window // Note: checkForUpdatesEngine gets deleted by // checkForUpdatesWindow... OpenCOR::CheckForUpdatesWindow checkForUpdatesWindow(checkForUpdatesEngine); settings.beginGroup(checkForUpdatesWindow.objectName()); checkForUpdatesWindow.loadSettings(&settings); settings.endGroup(); checkForUpdatesWindow.exec(); settings.beginGroup(checkForUpdatesWindow.objectName()); checkForUpdatesWindow.saveSettings(&settings); settings.endGroup(); } else { delete checkForUpdatesEngine; } } #endif // Initialise our colours by 'updating' them OpenCOR::updateColors(); // Create and show our splash screen, if we are not in debug mode #ifndef QT_DEBUG OpenCOR::SplashScreenWindow *splashScreen = new OpenCOR::SplashScreenWindow(); splashScreen->show(); #endif // Create our main window OpenCOR::MainWindow *win = new OpenCOR::MainWindow(guiApp, appDate); // Keep track of our main window (required by QtSingleApplication so that it // can do what it's supposed to be doing) guiApp->setActivationWindow(win); // Handle our arguments win->handleArguments(arguments); // Show our main window win->show(); // By default, we can and should execute our application bool canExecuteAplication = true; // Close and delete our splash screen once our main window is visible, if we // are not in debug mode #ifndef QT_DEBUG splashScreen->closeAndDeleteAfter(win); // Make sure that our main window is in the foreground, unless the user // decided to close our main window while we were showing our splash screen // Note: indeed, on Linux, to show our splash screen may result in our main // window being shown in the background... if (!win->shuttingDown()) win->showSelf(); else canExecuteAplication = false; #endif // Execute our application, if possible int res; if (canExecuteAplication) res = guiApp->exec(); else res = 0; // Keep track of our application file and directory paths (in case we need // to restart OpenCOR) QString appFilePath = guiApp->applicationFilePath(); QString appDirPath = guiApp->applicationDirPath(); // Delete our main window delete win; // We use QtWebKit, and QWebPage in particular, which results in some leak // messages being generated on Windows when leaving OpenCOR. This is because // an object cache is shared between all QWebPage instances. So to destroy a // QWebPage instance doesn't clear the cache, hence the leak messages. // However, those messages are 'only' warnings, so we can safely live with // them. Still, it doesn't look 'good', so we clear the memory caches, thus // avoiding those leak messages... // Note: the below must absolutely be done after calling guiApp->exec() and // before deleting guiApp... #ifdef Q_OS_WIN QWebSettings::clearMemoryCaches(); #endif // Remove all 'global' instances that were created and used during this // session OpenCOR::removeGlobalInstances(); // Delete our application delete guiApp; // We are done with the execution of our application, so now the question is // whether we need to restart // Note: we do this here rather than 'within' the GUI because once we have // launched a new instance of OpenCOR, we want this instance of // OpenCOR to finish as soon as possible, which will be the case here // since all that remains to be done is to return the result of the // execution of our application... if ((res == OpenCOR::CleanRestart) || (res == OpenCOR::NormalRestart)) { // We want to restart, so the question is whether we want a normal // restart or a clean one if (res == OpenCOR::CleanRestart) // We want a clean restart, so clear all the user settings (indeed, // this will ensure that the various windows are, for instance, // properly reset with regards to their dimensions) settings.clear(); // Restart OpenCOR, but without providing any of the arguments that were // originally passed to us since we want to reset everything QProcess::startDetached(appFilePath, QStringList(), appDirPath); } // We are done running the GUI version of OpenCOR, so leave return res; } //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>9101adea-2d14-11e5-af21-0401358ea401<commit_msg>9101adeb-2d14-11e5-af21-0401358ea401<commit_after>9101adeb-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include "EBSDMesh.h" template<> InputParameters validParams<EBSDMesh>() { InputParameters params = validParams<GeneratedMesh>(); params.addRequiredParam<FileName>("filename", "The name of the file containing the EBSD data"); params.addParam<unsigned int>("uniform_refine", 0, "Number of coarsening levels available in adaptive mesh refinement."); // suppress parameters params.suppressParameter<MooseEnum>("dim"); params.set<MooseEnum>("dim") = MooseEnum("1=1 2 3", "1"); params.suppressParameter<int>("nx"); params.suppressParameter<int>("ny"); params.suppressParameter<int>("nz"); params.suppressParameter<int>("xmin"); params.suppressParameter<int>("ymin"); params.suppressParameter<int>("zmin"); params.suppressParameter<int>("xmax"); params.suppressParameter<int>("ymax"); params.suppressParameter<int>("zmax"); return params; } EBSDMesh::EBSDMesh(const std::string & name, InputParameters parameters) : GeneratedMesh(name, parameters), _filename(getParam<FileName>("filename")) { if (isParamValid("nx") || isParamValid("ny") || isParamValid("nz") || isParamValid("xmin") || isParamValid("ymin") || isParamValid("zmin") || isParamValid("xmax") || isParamValid("ymax") || isParamValid("zmax")) mooseWarning("Do not specify mesh geometry information, it is read from the EBSD file."); } EBSDMesh::~EBSDMesh() { } void EBSDMesh::readEBSDHeader() { std::ifstream stream_in(_filename.c_str()); if (!stream_in) mooseError("Can't open EBSD file: " << _filename); // Labels to look for in the header std::vector<std::string> labels; labels.push_back("X_step"); labels.push_back("X_Dim"); labels.push_back("Y_step"); labels.push_back("Y_Dim"); labels.push_back("Z_step"); labels.push_back("Z_Dim"); // Dimension variables to store once they are found in the header // X_step, X_Dim, Y_step, Y_Dim, Z_step, Z_Dim // We use Reals even though the Dim values should all be integers... std::vector<Real> label_vals(labels.size()); std::string line; while (true) { // Try to a line form teh EBSD file std::getline(stream_in, line); if (stream_in) { // We need to process the comment lines that have: // X_step, X_Dim // Y_step, Y_Dim // Z_step, Z_Dim // in them. if (line.find("#") == 0) { // Process lines that start with a comment character (comments and meta data) for (unsigned i=0; i<labels.size(); ++i) if (line.find(labels[i]) != std::string::npos) { // Moose::out << "Found label " << labels[i] << ": " << line << std::endl; std::string dummy; std::istringstream iss(line); iss >> dummy >> dummy >> label_vals[i]; // One label per line, break out of for loop over labels break; } } else break; } else mooseError("Error reading EBSD file header in EBSDMesh."); } // Copy stuff out of the label_vars array into class variables _geometry.d[0] = label_vals[0]; _geometry.n[0] = label_vals[1]; _geometry.d[1] = label_vals[2]; _geometry.n[1] = label_vals[3]; _geometry.d[2] = label_vals[4]; _geometry.n[2] = label_vals[5]; unsigned int dim; // determine mesh dimension for (dim = 3; dim > 0 && _geometry.n[dim-1] == 0; --dim); // check if the data has nonzero stepsizes for (unsigned i = 0; i < dim; ++i) if (_geometry.d[i] == 0.0) mooseError("Error reading header, EBSD data step size is zero."); if (dim == 0) mooseError("Error reading header, EBSD data is zero dimensional."); _geometry.dim = dim; } void EBSDMesh::buildMesh() { readEBSDHeader(); unsigned int uniform_refine = getParam<unsigned int>("uniform_refine"); _dim = (_geometry.dim == 1 ? "1" : (_geometry.dim == 2 ? "2" : "3")); unsigned int nr[3]; nr[0] = _geometry.n[0]; nr[1] = _geometry.n[1]; nr[2] = _geometry.n[2]; // set min/max box length InputParameters & params = parameters(); params.set<Real>("xmin") = 0.0; params.set<Real>("xmax") = nr[0] * _geometry.d[0]; params.set<Real>("ymin") = 0.0; params.set<Real>("ymax") = nr[1] * _geometry.d[1]; params.set<Real>("zmin") = 0.0; params.set<Real>("zmax") = nr[2] * _geometry.d[2]; // check if the requested uniform refine level is possible and determine initial grid size for (unsigned int i = 0; i < uniform_refine; ++i) for (unsigned int j = 0; j < _geometry.dim; ++j) { if (nr[j] % 2 != 0) mooseError("EBSDMesh error. Requested uniform_refine levels not possible."); nr[j] /= 2; } _nx = nr[0]; _ny = nr[1]; _nz = nr[2]; GeneratedMesh::buildMesh(); } <commit_msg>Simplify EBSD header read for unit test (#27)<commit_after>#include "EBSDMesh.h" template<> InputParameters validParams<EBSDMesh>() { InputParameters params = validParams<GeneratedMesh>(); params.addRequiredParam<FileName>("filename", "The name of the file containing the EBSD data"); params.addParam<unsigned int>("uniform_refine", 0, "Number of coarsening levels available in adaptive mesh refinement."); // suppress parameters params.suppressParameter<MooseEnum>("dim"); params.set<MooseEnum>("dim") = MooseEnum("1=1 2 3", "1"); params.suppressParameter<int>("nx"); params.suppressParameter<int>("ny"); params.suppressParameter<int>("nz"); params.suppressParameter<int>("xmin"); params.suppressParameter<int>("ymin"); params.suppressParameter<int>("zmin"); params.suppressParameter<int>("xmax"); params.suppressParameter<int>("ymax"); params.suppressParameter<int>("zmax"); return params; } EBSDMesh::EBSDMesh(const std::string & name, InputParameters parameters) : GeneratedMesh(name, parameters), _filename(getParam<FileName>("filename")) { if (isParamValid("nx") || isParamValid("ny") || isParamValid("nz") || isParamValid("xmin") || isParamValid("ymin") || isParamValid("zmin") || isParamValid("xmax") || isParamValid("ymax") || isParamValid("zmax")) mooseWarning("Do not specify mesh geometry information, it is read from the EBSD file."); } EBSDMesh::~EBSDMesh() { } void EBSDMesh::readEBSDHeader() { std::ifstream stream_in(_filename.c_str()); if (!stream_in) mooseError("Can't open EBSD file: " << _filename); // Labels to look for in the header std::vector<std::string> labels; labels.push_back("X_step"); labels.push_back("X_Dim"); labels.push_back("Y_step"); labels.push_back("Y_Dim"); labels.push_back("Z_step"); labels.push_back("Z_Dim"); // Dimension variables to store once they are found in the header // X_step, X_Dim, Y_step, Y_Dim, Z_step, Z_Dim // We use Reals even though the Dim values should all be integers... std::vector<Real> label_vals(labels.size()); std::string line; while (std::getline(stream_in, line)) { // We need to process the comment lines that have: // X_step, X_Dim // Y_step, Y_Dim // Z_step, Z_Dim // in them. if (line.find("#") == 0) { // Process lines that start with a comment character (comments and meta data) for (unsigned i=0; i<labels.size(); ++i) if (line.find(labels[i]) != std::string::npos) { // Moose::out << "Found label " << labels[i] << ": " << line << std::endl; std::string dummy; std::istringstream iss(line); iss >> dummy >> dummy >> label_vals[i]; // One label per line, break out of for loop over labels break; } } else // first non comment line marks the end of the header break; } // Copy stuff out of the label_vars array into class variables _geometry.d[0] = label_vals[0]; _geometry.n[0] = label_vals[1]; _geometry.d[1] = label_vals[2]; _geometry.n[1] = label_vals[3]; _geometry.d[2] = label_vals[4]; _geometry.n[2] = label_vals[5]; unsigned int dim; // determine mesh dimension for (dim = 3; dim > 0 && _geometry.n[dim-1] == 0; --dim); // check if the data has nonzero stepsizes for (unsigned i = 0; i < dim; ++i) if (_geometry.d[i] == 0.0) mooseError("Error reading header, EBSD data step size is zero."); if (dim == 0) mooseError("Error reading header, EBSD data is zero dimensional."); _geometry.dim = dim; } void EBSDMesh::buildMesh() { readEBSDHeader(); unsigned int uniform_refine = getParam<unsigned int>("uniform_refine"); _dim = (_geometry.dim == 1 ? "1" : (_geometry.dim == 2 ? "2" : "3")); unsigned int nr[3]; nr[0] = _geometry.n[0]; nr[1] = _geometry.n[1]; nr[2] = _geometry.n[2]; // set min/max box length InputParameters & params = parameters(); params.set<Real>("xmin") = 0.0; params.set<Real>("xmax") = nr[0] * _geometry.d[0]; params.set<Real>("ymin") = 0.0; params.set<Real>("ymax") = nr[1] * _geometry.d[1]; params.set<Real>("zmin") = 0.0; params.set<Real>("zmax") = nr[2] * _geometry.d[2]; // check if the requested uniform refine level is possible and determine initial grid size for (unsigned int i = 0; i < uniform_refine; ++i) for (unsigned int j = 0; j < _geometry.dim; ++j) { if (nr[j] % 2 != 0) mooseError("EBSDMesh error. Requested uniform_refine levels not possible."); nr[j] /= 2; } _nx = nr[0]; _ny = nr[1]; _nz = nr[2]; GeneratedMesh::buildMesh(); } <|endoftext|>
<commit_before>6c9128b6-2fa5-11e5-8ef5-00012e3d3f12<commit_msg>6c92fd74-2fa5-11e5-bfe2-00012e3d3f12<commit_after>6c92fd74-2fa5-11e5-bfe2-00012e3d3f12<|endoftext|>
<commit_before>#include <iostream> #include <curses.h> #include <cmath> #include <algorithm> #include "Connection.h" #include "Configuration.h" static std::vector<Connection> connections; void offending() { std::vector<Process> processes; for (Connection& conn : connections) { if (!conn) break; std::vector<Process> process = conn.getOS()->getProcesses(); for (Process& p : process) processes.push_back(p); } std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool { return a.time > b.time; }); clear(); refresh(); int maxx, maxy; getmaxyx(stdscr, maxy, maxx); char action; do { clear(); mvaddstr(0,0, "Host"); mvaddstr(0,20, "Program"); mvaddstr(0,40, "User"); mvaddstr(0,50, "PID"); mvaddstr(0,60, "CPU"); mvaddstr(0,66, "MEM"); mvaddstr(0,72, "Time"); int row = 1; for (Process& p : processes) { mvaddnstr(row, 0, p.connection->getHostname().c_str(), 19); mvaddnstr(row, 20, p.command.c_str(), 19); mvaddnstr(row, 40, p.user.c_str(), 10); mvaddnstr(row, 50, std::to_string(p.pid).c_str(), 10); mvaddnstr(row, 60, std::to_string(p.cpu).c_str(), 5); mvaddnstr(row, 66, std::to_string(p.mem).c_str(), 5); mvaddnstr(row, 72, std::to_string(p.time / 60.0 / 60.0).c_str(), 8); row++; if (row == maxy) break; } refresh(); action = getchar(); if (action == 'c') { std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool { return a.cpu > b.cpu; }); } else if (action == 'm') { std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool { return a.mem > b.mem; }); } } while (action != 'q'); } int main(int argc, char** argv) { Configuration conf; connections.reserve(conf.getHosts().size()); for (std::string hostname : conf.getHosts()) { std::cout << hostname << std::endl; connections.emplace_back( hostname ); } for (Connection& conn : connections) { if (!conn) { std::cerr << "Error!" << std::endl; continue; } OperatingSystem * os = conn.getOS(); auto loads = os->getLoad(); for (double load : loads) { std::cout << load << " "; } std::cout << std::endl; } setlocale(LC_ALL, "en_US.UTF-8"); initscr(); timeout(1000); char action; do { int row = 1; attron(A_DIM); mvaddstr(0, 0, "Hostname"); mvaddstr(0,40, "| Load"); mvaddstr(0,47, "| #usr"); attroff(A_DIM); start_color(); init_pair(1, COLOR_RED, COLOR_BLACK); std::string progress = "|/-\\"; int prog = 0; attron(A_STANDOUT); mvaddch(0, 79, progress[prog]); attroff(A_STANDOUT); for (Connection & conn : connections) { mvaddstr(row, 1, conn.getHostname().c_str()); mvaddch(row, 40, '|'); if (!conn) { attron(A_BLINK | COLOR_PAIR(1)); addstr(" OFFLINE "); attroff(A_BLINK | COLOR_PAIR(1)); continue; } std::array<double,3> load = conn.getOS()->getLoad(); std::array<double,5> interp; interp[0] = load[0]; interp[1] = (load[0] + load[1])/2; interp[2] = load[1]; interp[3] = (load[1] + load[2])/2; interp[4] = load[2]; cchar_t t; t.attr = 0; t.chars[1] = L'\0'; for (double load : interp) { int loadScaled = (int)( std::log(load)/std::log(10) * 4 + 6 ); loadScaled = loadScaled > 7 ? 7 : loadScaled; loadScaled = loadScaled < 0 ? 0 : loadScaled; t.chars[0] = L'\u2581'+ loadScaled ; add_wch( &t ); } mvaddstr(row, 47, "| "); addstr( std::to_string( conn.getOS()->getNUsers() ).c_str() ); row++; } refresh(); row = 1; prog++; if (prog == 4) prog = 0; action = getch(); if (action == 'o') { offending(); clear(); } } while (action != 'q'); endwin(); return 0; }<commit_msg>Changed to days.<commit_after>#include <iostream> #include <curses.h> #include <cmath> #include <algorithm> #include "Connection.h" #include "Configuration.h" static std::vector<Connection> connections; void offending() { std::vector<Process> processes; for (Connection& conn : connections) { if (!conn) break; std::vector<Process> process = conn.getOS()->getProcesses(); for (Process& p : process) processes.push_back(p); } std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool { return a.time > b.time; }); clear(); refresh(); int maxx, maxy; getmaxyx(stdscr, maxy, maxx); char action; do { clear(); mvaddstr(0,0, "Host"); mvaddstr(0,20, "Program"); mvaddstr(0,40, "User"); mvaddstr(0,50, "PID"); mvaddstr(0,60, "CPU"); mvaddstr(0,66, "MEM"); mvaddstr(0,72, "Time"); int row = 1; for (Process& p : processes) { mvaddnstr(row, 0, p.connection->getHostname().c_str(), 19); mvaddnstr(row, 20, p.command.c_str(), 19); mvaddnstr(row, 40, p.user.c_str(), 10); mvaddnstr(row, 50, std::to_string(p.pid).c_str(), 10); mvaddnstr(row, 60, std::to_string(p.cpu).c_str(), 5); mvaddnstr(row, 66, std::to_string(p.mem).c_str(), 5); mvaddnstr(row, 72, std::to_string(p.time / (60.0 * 60.0 * 24.0)).c_str(), 8); row++; if (row == maxy) break; } refresh(); action = getchar(); if (action == 'c') { std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool { return a.cpu > b.cpu; }); } else if (action == 'm') { std::sort(processes.begin(), processes.end(), [](Process a, Process b) -> bool { return a.mem > b.mem; }); } } while (action != 'q'); } int main(int argc, char** argv) { Configuration conf; connections.reserve(conf.getHosts().size()); for (std::string hostname : conf.getHosts()) { std::cout << hostname << std::endl; connections.emplace_back( hostname ); } for (Connection& conn : connections) { if (!conn) { std::cerr << "Error!" << std::endl; continue; } OperatingSystem * os = conn.getOS(); auto loads = os->getLoad(); for (double load : loads) { std::cout << load << " "; } std::cout << std::endl; } setlocale(LC_ALL, "en_US.UTF-8"); initscr(); timeout(1000); char action; do { int row = 1; attron(A_DIM); mvaddstr(0, 0, "Hostname"); mvaddstr(0,40, "| Load"); mvaddstr(0,47, "| #usr"); attroff(A_DIM); start_color(); init_pair(1, COLOR_RED, COLOR_BLACK); std::string progress = "|/-\\"; int prog = 0; attron(A_STANDOUT); mvaddch(0, 79, progress[prog]); attroff(A_STANDOUT); for (Connection & conn : connections) { mvaddstr(row, 1, conn.getHostname().c_str()); mvaddch(row, 40, '|'); if (!conn) { attron(A_BLINK | COLOR_PAIR(1)); addstr(" OFFLINE "); attroff(A_BLINK | COLOR_PAIR(1)); continue; } std::array<double,3> load = conn.getOS()->getLoad(); std::array<double,5> interp; interp[0] = load[0]; interp[1] = (load[0] + load[1])/2; interp[2] = load[1]; interp[3] = (load[1] + load[2])/2; interp[4] = load[2]; cchar_t t; t.attr = 0; t.chars[1] = L'\0'; for (double load : interp) { int loadScaled = (int)( std::log(load)/std::log(10) * 4 + 6 ); loadScaled = loadScaled > 7 ? 7 : loadScaled; loadScaled = loadScaled < 0 ? 0 : loadScaled; t.chars[0] = L'\u2581'+ loadScaled ; add_wch( &t ); } mvaddstr(row, 47, "| "); addstr( std::to_string( conn.getOS()->getNUsers() ).c_str() ); row++; } refresh(); row = 1; prog++; if (prog == 4) prog = 0; action = getch(); if (action == 'o') { offending(); clear(); } } while (action != 'q'); endwin(); return 0; }<|endoftext|>
<commit_before>#include "project.h" #include "main_window.h" #include <QDebug> #include <QApplication> #include <QFileInfo> #include <QDir> #include <QVideoWidget> #include <QMediaPlayer> int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setApplicationName(APP_NAME); a.setApplicationDisplayName(APP_NAME); a.setOrganizationName(COPYRIGHT_HOLDER); a.setOrganizationDomain(COPYRIGHT_DOMAIN); a.setWindowIcon(QIcon(":/logo/images/logo_512.png")); MainWindow w; QString path; if(argc<2) { QTextStream(stdout) << "Usage: " << QFileInfo( QCoreApplication::applicationFilePath() ).fileName() << " path_to_dir_or_file" << endl; } else { path = QString(argv[1]); QFileInfo fileinfo(path); if(!fileinfo.exists()) { qDebug() << "File does not exist: " << path; return 1; } qDebug() << path; if(fileinfo.isDir()) w.loadFolder(fileinfo.filePath()); else w.loadFolder(fileinfo.absoluteDir().absolutePath(), fileinfo.fileName()); } w.show(); return a.exec(); } <commit_msg>Made window show centered in primary monitor<commit_after>#include "project.h" #include "main_window.h" #include <QDebug> #include <QApplication> #include <QFileInfo> #include <QDir> #include <QVideoWidget> #include <QMediaPlayer> #include <QDesktopWidget> int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setApplicationName(APP_NAME); a.setApplicationDisplayName(APP_NAME); a.setOrganizationName(COPYRIGHT_HOLDER); a.setOrganizationDomain(COPYRIGHT_DOMAIN); a.setWindowIcon(QIcon(":/logo/images/logo_512.png")); MainWindow w; QString path; if(argc<2) { QTextStream(stdout) << "Usage: " << QFileInfo( QCoreApplication::applicationFilePath() ).fileName() << " path_to_dir_or_file" << endl; } else { path = QString(argv[1]); QFileInfo fileinfo(path); if(!fileinfo.exists()) { qDebug() << "File does not exist: " << path; return 1; } qDebug() << path; if(fileinfo.isDir()) w.loadFolder(fileinfo.filePath()); else w.loadFolder(fileinfo.absoluteDir().absolutePath(), fileinfo.fileName()); } w.move(QApplication::desktop()->screenGeometry().center() - w.rect().center()); w.show(); return a.exec(); } <|endoftext|>
<commit_before>#include "image_writer.h" #include "heatmap_writer.h" #include "json_writer.h" #include "logger.h" #include "parser.h" #include "logger.h" #include <boost/format.hpp> #include <boost/program_options.hpp> #include <fstream> #include <float.h> using namespace wotreplay; namespace po = boost::program_options; void show_help(int argc, const char *argv[], po::options_description &desc) { std::stringstream help_message; help_message << desc << "\n"; logger.write(help_message.str()); } float distance(const std::tuple<float, float, float> &left, const std::tuple<float, float, float> &right) { float delta_x = std::get<0>(left) - std::get<0>(right); float delta_y = std::get<1>(left) - std::get<1>(right); float delta_z = std::get<2>(left) - std::get<2>(right); // distance in xy plane float dist1 = std::sqrt(delta_x*delta_x + delta_y*delta_y); return std::sqrt(dist1*dist1 + delta_z*delta_z); } static bool is_not_empty(const packet_t &packet) { // list of default properties with no special meaning std::set<property_t> standard_properties = { property_t::clock, property_t::player_id, property_t::type, property_t::sub_type }; auto properties = packet.get_properties(); for (int i = 0; i < properties.size(); ++i) { property_t property = static_cast<property_t>(i); // packet has property, but can not be found in default properties if (properties[i] && standard_properties.find(property) == standard_properties.end()) { return true; } } return false; } int create_minimaps(const po::variables_map &vm, const std::string &output, bool debug) { if ( vm.count("output") == 0 ) { logger.write(wotreplay::log_level_t::error, "parameter output is required to use this mode"); return -EXIT_FAILURE; } boost::format file_name_format("%1%/%2%_%3%_%4%.png"); image_writer_t writer; for (const auto &arena_entry : get_arenas()) { const arena_t &arena = arena_entry.second; for (const auto &configuration_entry : arena.configurations) { for (int team_id : { 0, 1 }) { const std::string game_mode = configuration_entry.first; writer.init(arena, game_mode); writer.set_recorder_team(team_id); writer.set_use_fixed_teamcolors(false); std::string file_name = (file_name_format % output % arena.name % game_mode % team_id).str(); std::ofstream os(file_name, std::ios::binary); writer.finish(); writer.write(os); } } } return EXIT_SUCCESS; } int parse_replay(const po::variables_map &vm, const std::string &input, const std::string &output, const std::string &type, bool debug) { if ( !(vm.count("type") > 0 && vm.count("input") > 0) ) { logger.write(wotreplay::log_level_t::error, "parameters type and input are required to use this mode\n"); return -EXIT_FAILURE; } std::ifstream in(input, std::ios::binary); if (!in) { logger.writef(log_level_t::error, "Something went wrong with opening file: %1%\n", input); std::exit(0); } parser_t parser; game_t game; parser.set_debug(debug); parser.load_data(); parser.parse(in, game); std::unique_ptr<writer_t> writer; if (type == "png") { writer = std::unique_ptr<writer_t>(new image_writer_t()); auto &image_writer = dynamic_cast<image_writer_t&>(*writer); image_writer.set_show_self(true); image_writer.set_use_fixed_teamcolors(false); } else if (type == "json") { writer = std::unique_ptr<writer_t>(new json_writer_t()); if (vm.count("supress-empty")) { writer->set_filter(&is_not_empty); } } else if (type == "heatmap") { writer = std::unique_ptr<writer_t>(new heatmap_writer_t()); } else { logger.writef(log_level_t::error, "Invalid output type (%1%), supported types: png and json.\n", type); return -EXIT_FAILURE; } writer->init(game.get_arena(), game.get_game_mode()); writer->update(game); writer->finish(); std::ostream *out; if (vm.count("output") > 0) { out = new std::ofstream(output, std::ios::binary); if (!out) { logger.writef(log_level_t::error, "Something went wrong with opening file: %1%\n", input); std::exit(0); } } else { out = &std::cout; } writer->write(*out); if (dynamic_cast<std::ofstream*>(out)) { dynamic_cast<std::ofstream*>(out)->close(); delete out; } return EXIT_SUCCESS; } int main(int argc, const char * argv[]) { po::options_description desc("Allowed options"); std::string type, output, input, root; desc.add_options() ("type" , po::value(&type), "select output type") ("output", po::value(&output), "target file") ("input" , po::value(&input), "input file") ("root" , po::value(&root), "set root directory") ("help" , "produce help message") ("debug" , "enable parser debugging") ("supress-empty", "supress empty packets from json output") ("create-minimaps", "create all empty minimaps in output directory") ("parse", "parse a replay file") ("quiet", "supress diagnostic messages"); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (std::exception &e) { show_help(argc, argv, desc); std::exit(-1); } catch (...) { logger.write(log_level_t::error, "Unknown error.\n"); std::exit(-1); } if (vm.count("help") > 0) { show_help(argc, argv, desc); std::exit(0); } if (vm.count("root") > 0 && chdir(root.c_str()) != 0) { logger.writef(log_level_t::error, "Cannot change working directory to: %1%\n", root); std::exit(0); } bool debug = vm.count("debug") > 0; if (debug) { logger.set_log_level(log_level_t::debug); } else if (vm.count("quiet") > 0) { logger.set_log_level(log_level_t::none); } else { logger.set_log_level(log_level_t::warning); } int exit_code; if (vm.count("parse") > 0) { // parse exit_code = parse_replay(vm, input, output, type, debug); } else if (vm.count("create-minimaps") > 0) { // create all minimaps exit_code = create_minimaps(vm, output, debug); } else { logger.write(wotreplay::log_level_t::error, "Error: no mode specified\n"); exit_code = -EXIT_FAILURE; } if (exit_code < 0) { show_help(argc, argv, desc); } return exit_code; }<commit_msg>Improve error message for failing to open input file<commit_after>#include "image_writer.h" #include "heatmap_writer.h" #include "json_writer.h" #include "logger.h" #include "parser.h" #include "logger.h" #include <boost/format.hpp> #include <boost/program_options.hpp> #include <fstream> #include <float.h> using namespace wotreplay; namespace po = boost::program_options; void show_help(int argc, const char *argv[], po::options_description &desc) { std::stringstream help_message; help_message << desc << "\n"; logger.write(help_message.str()); } float distance(const std::tuple<float, float, float> &left, const std::tuple<float, float, float> &right) { float delta_x = std::get<0>(left) - std::get<0>(right); float delta_y = std::get<1>(left) - std::get<1>(right); float delta_z = std::get<2>(left) - std::get<2>(right); // distance in xy plane float dist1 = std::sqrt(delta_x*delta_x + delta_y*delta_y); return std::sqrt(dist1*dist1 + delta_z*delta_z); } static bool is_not_empty(const packet_t &packet) { // list of default properties with no special meaning std::set<property_t> standard_properties = { property_t::clock, property_t::player_id, property_t::type, property_t::sub_type }; auto properties = packet.get_properties(); for (int i = 0; i < properties.size(); ++i) { property_t property = static_cast<property_t>(i); // packet has property, but can not be found in default properties if (properties[i] && standard_properties.find(property) == standard_properties.end()) { return true; } } return false; } int create_minimaps(const po::variables_map &vm, const std::string &output, bool debug) { if ( vm.count("output") == 0 ) { logger.write(wotreplay::log_level_t::error, "parameter output is required to use this mode"); return -EXIT_FAILURE; } boost::format file_name_format("%1%/%2%_%3%_%4%.png"); image_writer_t writer; for (const auto &arena_entry : get_arenas()) { const arena_t &arena = arena_entry.second; for (const auto &configuration_entry : arena.configurations) { for (int team_id : { 0, 1 }) { const std::string game_mode = configuration_entry.first; writer.init(arena, game_mode); writer.set_recorder_team(team_id); writer.set_use_fixed_teamcolors(false); std::string file_name = (file_name_format % output % arena.name % game_mode % team_id).str(); std::ofstream os(file_name, std::ios::binary); writer.finish(); writer.write(os); } } } return EXIT_SUCCESS; } int parse_replay(const po::variables_map &vm, const std::string &input, const std::string &output, const std::string &type, bool debug) { if ( !(vm.count("type") > 0 && vm.count("input") > 0) ) { logger.write(wotreplay::log_level_t::error, "parameters type and input are required to use this mode\n"); return -EXIT_FAILURE; } std::ifstream in(input, std::ios::binary); if (!in) { logger.writef(log_level_t::error, "Failed to open file: %1%\n", input); std::exit(0); } parser_t parser; game_t game; parser.set_debug(debug); parser.load_data(); parser.parse(in, game); std::unique_ptr<writer_t> writer; if (type == "png") { writer = std::unique_ptr<writer_t>(new image_writer_t()); auto &image_writer = dynamic_cast<image_writer_t&>(*writer); image_writer.set_show_self(true); image_writer.set_use_fixed_teamcolors(false); } else if (type == "json") { writer = std::unique_ptr<writer_t>(new json_writer_t()); if (vm.count("supress-empty")) { writer->set_filter(&is_not_empty); } } else if (type == "heatmap") { writer = std::unique_ptr<writer_t>(new heatmap_writer_t()); } else { logger.writef(log_level_t::error, "Invalid output type (%1%), supported types: png and json.\n", type); return -EXIT_FAILURE; } writer->init(game.get_arena(), game.get_game_mode()); writer->update(game); writer->finish(); std::ostream *out; if (vm.count("output") > 0) { out = new std::ofstream(output, std::ios::binary); if (!out) { logger.writef(log_level_t::error, "Something went wrong with opening file: %1%\n", input); std::exit(0); } } else { out = &std::cout; } writer->write(*out); if (dynamic_cast<std::ofstream*>(out)) { dynamic_cast<std::ofstream*>(out)->close(); delete out; } return EXIT_SUCCESS; } int main(int argc, const char * argv[]) { po::options_description desc("Allowed options"); std::string type, output, input, root; desc.add_options() ("type" , po::value(&type), "select output type") ("output", po::value(&output), "target file") ("input" , po::value(&input), "input file") ("root" , po::value(&root), "set root directory") ("help" , "produce help message") ("debug" , "enable parser debugging") ("supress-empty", "supress empty packets from json output") ("create-minimaps", "create all empty minimaps in output directory") ("parse", "parse a replay file") ("quiet", "supress diagnostic messages"); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (std::exception &e) { show_help(argc, argv, desc); std::exit(-1); } catch (...) { logger.write(log_level_t::error, "Unknown error.\n"); std::exit(-1); } if (vm.count("help") > 0) { show_help(argc, argv, desc); std::exit(0); } if (vm.count("root") > 0 && chdir(root.c_str()) != 0) { logger.writef(log_level_t::error, "Cannot change working directory to: %1%\n", root); std::exit(0); } bool debug = vm.count("debug") > 0; if (debug) { logger.set_log_level(log_level_t::debug); } else if (vm.count("quiet") > 0) { logger.set_log_level(log_level_t::none); } else { logger.set_log_level(log_level_t::warning); } int exit_code; if (vm.count("parse") > 0) { // parse exit_code = parse_replay(vm, input, output, type, debug); } else if (vm.count("create-minimaps") > 0) { // create all minimaps exit_code = create_minimaps(vm, output, debug); } else { logger.write(wotreplay::log_level_t::error, "Error: no mode specified\n"); exit_code = -EXIT_FAILURE; } if (exit_code < 0) { show_help(argc, argv, desc); } return exit_code; }<|endoftext|>
<commit_before>6e05fa1e-2e4f-11e5-aa1f-28cfe91dbc4b<commit_msg>6e106ea3-2e4f-11e5-84d1-28cfe91dbc4b<commit_after>6e106ea3-2e4f-11e5-84d1-28cfe91dbc4b<|endoftext|>
<commit_before>#include <cmath> #include <iostream> #include <memory> #include <sstream> #include <thread> #include "camera/perspective.h" #include "engine/cosine_debugger.h" #include "geom/point.h" #include "geom/rectangle.h" #include "geom/vector.h" #include "image/image.h" #include "model/obj.h" #include "node/group/simple.h" #include "node/instance.h" #include "node/solid/disc.h" #include "node/solid/infinite_plane.h" #include "node/solid/sphere.h" #include "node/solid/triangle.h" #include "renderer/parallel/parallel.h" #include "renderer/serial/serial.h" #include "renderer/settings.h" #include "supersampling/random.h" #include "world/world.h" using namespace Svit; int main (void) { Settings settings; settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.max_thread_count = std::thread::hardware_concurrency(); settings.tile_size = Vector2i(10, 10); settings.max_sample_count = 1; settings.adaptive_sample_step = 10; CosineDebuggerEngine engine; SerialRenderer renderer; RandomSuperSampling super_sampling(true); SimpleGroup scene; Sphere sphere(Point3(0.0, 0.0, 0.0), 1.0); PerspectiveCamera camera( Point3(0.0, 0.75, -5.5), Vector3(0.0, 0.0, 1.0), Vector3(0.0, 1.0, 0.0), Rectangle(Point2i(0, 0), Vector2i(128, 72)).get_aspect_ratio(), M_PI/2.0f); ObjModel cow; cow.load("cow.obj"); SimpleGroup cow_group; cow.add_to_group(cow_group); scene.add(&sphere); scene.add(&cow_group); World world; world.scene = &scene; world.camera = &camera; Image image = renderer.render(world, settings, engine, super_sampling); image.write_png(std::string("cow.png")); return 0; } <commit_msg>WIP main.cpp<commit_after>#include <cmath> #include <iostream> #include <memory> #include <sstream> #include <thread> #include "camera/perspective.h" #include "engine/cosine_debugger.h" #include "geom/point.h" #include "geom/rectangle.h" #include "geom/vector.h" #include "image/image.h" #include "model/obj.h" #include "node/group/simple.h" #include "node/group/kdtree/kdtree.h" #include "node/group/kdtree/axis_selector/round_robin.h" #include "node/group/kdtree/split_strategy/centre.h" #include "node/group/kdtree/kdtree.h" #include "node/instance.h" #include "node/solid/disc.h" #include "node/solid/infinite_plane.h" #include "node/solid/sphere.h" #include "node/solid/triangle.h" #include "renderer/parallel/parallel.h" #include "renderer/serial/serial.h" #include "renderer/settings.h" #include "supersampling/random.h" #include "world/world.h" using namespace Svit; int main (void) { Settings settings; settings.whole_area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.area = Rectangle(Point2i(0, 0), Vector2i(1280, 720)); settings.max_thread_count = std::thread::hardware_concurrency(); settings.tile_size = Vector2i(10, 10); settings.max_sample_count = 1; settings.adaptive_sample_step = 10; CosineDebuggerEngine engine; SerialRenderer renderer; RandomSuperSampling super_sampling(true); SimpleGroup scene; Sphere sphere(Point3(0.0, 0.0, 0.0), 1.0); PerspectiveCamera camera( Point3(0.0, 0.75, -5.5), Vector3(0.0, 0.0, 1.0), Vector3(0.0, 1.0, 0.0), Rectangle(Point2i(0, 0), Vector2i(128, 72)).get_aspect_ratio(), M_PI/2.0f); ObjModel cow_model; cow_model.load("simplecow.obj"); KDTree cow(new RoundRobinAxisSelector(), new CentreSplitStrategy(), 20, 3); cow_model.add_to_group(cow); cow.finish(); cow.root.bounding_box.max.dump("cow bb min"); cow.root.bounding_box.min.dump("cow bb max"); /* KDTree spheres(new RoundRobinAxisSelector(), new CentreSplitStrategy(), 20, 100); */ /* for (unsigned int i = 0; i < 6; i++) */ /* spheres.add(new Sphere(Point3((float)i/5.0f*10.0f, 0.0f, 0.0f), 1.0f)); */ /* spheres.finish(); */ /* scene.add(&spheres); */ scene.add(&cow); /* scene.add(&sphere); */ World world; world.scene = &scene; world.camera = &camera; Image image = renderer.render(world, settings, engine, super_sampling); image.write_png(std::string("coww.png")); return 0; } <|endoftext|>
<commit_before>#include "config.h" #include "dbmanager.h" #include "iconmanager.h" #include "mainwindow.h" #include "plugins/pluginmanager.h" #include "sqlhighlighter.h" #include "tabwidget/abstracttabwidget.h" #include "tools/logger.h" #include "widgets/querytextedit.h" #include <QtWidgets/QApplication> #include <QtWidgets/QSplashScreen> int main(int argc, char *argv[]) { QApplication::setApplicationName("dbmaster"); QApplication::setApplicationVersion("0.10.0"); QApplication::setOrganizationDomain("dbmaster.org"); QApplication a(argc, argv); a.setWindowIcon(QIcon(":/img/dbmaster.png")); QSplashScreen splash(QPixmap(":/img/splash.png")); splash.show(); Logger *logger = new Logger; // Loading translations splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom); QTranslator translator; // getting the current locale QString lang = QLocale::system().name().left(2); QString transdir = "."; #if defined(Q_WS_X11) // for *nix transdir = QString(PREFIX).append("/share/dbmaster/tr"); #endif #if defined(Q_OS_MAC) transdir = "DbMaster.app/Contents/MacOS"; #endif QString path; /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en * dev, on le charge, sinon il est dans le répertoire d'installation. */ path = QString("../../dbmaster/tr/%1.qm").arg(lang); if (!QFile::exists(path)) path = transdir.append("/%1.qm").arg(lang); qDebug() << QString("Loaded %1 translation file").arg(path); translator.load(path); a.installTranslator(&translator); path = QLibraryInfo::location(QLibraryInfo::TranslationsPath); #if defined (Q_WS_WIN) path = QDir::currentPath(); #endif QTranslator qtTranslator; qtTranslator.load("qt_" + lang, path); a.installTranslator(&qtTranslator); // Ajout des plugins splash.showMessage(QObject::tr("Loading plugins..."), Qt::AlignBottom); PluginManager::init(); splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom); IconManager::init(); DbManager::init(); Config::init(); QueryTextEdit::reloadCompleter(); MainWindow *w = new MainWindow(); w->show(); splash.finish(w); if (a.arguments().size() >= 2) { for (int i=1; i<a.arguments().size(); i++) { w->openQuery(a.arguments()[i]); } } return a.exec(); } <commit_msg>Version number<commit_after>#include "config.h" #include "dbmanager.h" #include "iconmanager.h" #include "mainwindow.h" #include "plugins/pluginmanager.h" #include "sqlhighlighter.h" #include "tabwidget/abstracttabwidget.h" #include "tools/logger.h" #include "widgets/querytextedit.h" #include <QtWidgets/QApplication> #include <QtWidgets/QSplashScreen> int main(int argc, char *argv[]) { QApplication::setApplicationName("dbmaster"); QApplication::setApplicationVersion("0.11.0"); QApplication::setOrganizationDomain("dbmaster.org"); QApplication a(argc, argv); a.setWindowIcon(QIcon(":/img/dbmaster.png")); QSplashScreen splash(QPixmap(":/img/splash.png")); splash.show(); Logger *logger = new Logger; // Loading translations splash.showMessage(QObject::tr("Loading translations..."), Qt::AlignBottom); QTranslator translator; // getting the current locale QString lang = QLocale::system().name().left(2); QString transdir = "."; #if defined(Q_WS_X11) // for *nix transdir = QString(PREFIX).append("/share/dbmaster/tr"); #endif #if defined(Q_OS_MAC) transdir = "DbMaster.app/Contents/MacOS"; #endif QString path; /* on teste d'abord si le .qm est dans le dossier courant -> alors on est en * dev, on le charge, sinon il est dans le répertoire d'installation. */ path = QString("../../dbmaster/tr/%1.qm").arg(lang); if (!QFile::exists(path)) path = transdir.append("/%1.qm").arg(lang); qDebug() << QString("Loaded %1 translation file").arg(path); translator.load(path); a.installTranslator(&translator); path = QLibraryInfo::location(QLibraryInfo::TranslationsPath); #if defined (Q_WS_WIN) path = QDir::currentPath(); #endif QTranslator qtTranslator; qtTranslator.load("qt_" + lang, path); a.installTranslator(&qtTranslator); // Ajout des plugins splash.showMessage(QObject::tr("Loading plugins..."), Qt::AlignBottom); PluginManager::init(); splash.showMessage(QObject::tr("Initialization..."), Qt::AlignBottom); IconManager::init(); DbManager::init(); Config::init(); QueryTextEdit::reloadCompleter(); MainWindow *w = new MainWindow(); w->show(); splash.finish(w); if (a.arguments().size() >= 2) { for (int i=1; i<a.arguments().size(); i++) { w->openQuery(a.arguments()[i]); } } return a.exec(); } <|endoftext|>
<commit_before>8c3d20e4-2d14-11e5-af21-0401358ea401<commit_msg>8c3d20e5-2d14-11e5-af21-0401358ea401<commit_after>8c3d20e5-2d14-11e5-af21-0401358ea401<|endoftext|>
<commit_before>#include <cstdio> #include <cstring> #include <em_chip.h> #include <em_cmu.h> #include <em_dbg.h> #include <em_device.h> #include <em_emu.h> #include <em_gpio.h> #include <gsl/span> #include <em_system.h> #include <FreeRTOS.h> #include <FreeRTOSConfig.h> #include <task.h> #include "SwoEndpoint/SwoEndpoint.h" #include "adcs/adcs.h" #include "base/ecc.h" #include "base/os.h" #include "dmadrv.h" #include "eps/eps.h" #include "fs/fs.h" #include "i2c/i2c.h" #include "io_map.h" #include "leuart/leuart.h" #include "logger/logger.h" #include "mission.h" #include "obc.h" #include "storage/nand.h" #include "storage/nand_driver.h" #include "storage/storage.h" #include "swo/swo.h" #include "system.h" #include "terminal.h" #include "gpio/gpio.h" #include "leuart/leuart.h" #include "power_eps/power_eps.h" using services::time::TimeProvider; using namespace std::chrono_literals; OBC Main; mission::ObcMission Mission(Main.timeProvider, Main.antennaDriver, false); const int __attribute__((used)) uxTopUsedPriority = configMAX_PRIORITIES; extern "C" void vApplicationStackOverflowHook(xTaskHandle* pxTask, signed char* pcTaskName) { UNREFERENCED_PARAMETER(pxTask); UNREFERENCED_PARAMETER(pcTaskName); } extern "C" void vApplicationIdleHook(void) { EMU_EnterEM1(); } void I2C0_IRQHandler(void) { Main.Hardware.I2C.Peripherals[0].Driver.IRQHandler(); } void I2C1_IRQHandler(void) { Main.Hardware.I2C.Peripherals[1].Driver.IRQHandler(); } static void BlinkLed0(void* param) { UNREFERENCED_PARAMETER(param); while (1) { Main.Hardware.Pins.Led0.Toggle(); vTaskDelay(1000 / portTICK_PERIOD_MS); } } static void SmartWaitTask(void* param) { UNREFERENCED_PARAMETER(param); LOG(LOG_LEVEL_DEBUG, "Wait start"); while (1) { Main.timeProvider.LongDelay(10min); LOG(LOG_LEVEL_DEBUG, "After wait"); } } static void InitSwoEndpoint(void) { void* swoEndpointHandle = SwoEndpointInit(); const bool result = LogAddEndpoint(SwoGetEndpoint(swoEndpointHandle), swoEndpointHandle, LOG_LEVEL_TRACE); if (!result) { SwoPutsOnChannel(0, "Unable to attach swo endpoint to logger. "); } } static void ClearState(OBC* obc) { if (obc->Hardware.Pins.SysClear.Input() == false) { LOG(LOG_LEVEL_WARNING, "Clearing state on startup"); if (OS_RESULT_FAILED(obc->Storage.ClearStorage())) { LOG(LOG_LEVEL_ERROR, "Clearing state failed"); } LOG(LOG_LEVEL_INFO, "All files removed"); } } static void SetupAntennas(void) { AntennaMiniportInitialize(&Main.antennaMiniport); AntennaDriverInitialize(&Main.antennaDriver, &Main.antennaMiniport, &Main.Hardware.I2C.Buses.Bus, &Main.Hardware.I2C.Buses.Payload); } static void ObcInitTask(void* param) { auto obc = static_cast<OBC*>(param); obc->PostStartInitialization(); ClearState(obc); if (!obc->timeProvider.Initialize(nullptr, nullptr)) { LOG(LOG_LEVEL_ERROR, "Unable to initialize persistent timer. "); } if (OS_RESULT_FAILED(Main.antennaDriver.HardReset(&Main.antennaDriver))) { LOG(LOG_LEVEL_ERROR, "Unable to reset both antenna controllers. "); } if (!obc->Communication.CommDriver.Restart()) { LOG(LOG_LEVEL_ERROR, "Unable to restart comm"); } InitializeADCS(&obc->adcs); Mission.Initialize(); System::CreateTask(SmartWaitTask, "SmartWait", 512, NULL, TaskPriority::P1, NULL); LOG(LOG_LEVEL_INFO, "Intialized"); Main.initialized = true; System::SuspendTask(NULL); } void SetupHardware(void) { CMU_ClockEnable(cmuClock_GPIO, true); CMU_ClockEnable(cmuClock_DMA, true); CMU_ClockSelectSet(cmuClock_LFA, cmuSelect_HFCLKLE); CMU_ClockSelectSet(cmuClock_LFB, cmuSelect_HFCLKLE); } extern "C" void __libc_init_array(void); int main(void) { memset(&Main, 0, sizeof(Main)); __libc_init_array(); CHIP_Init(); SetupHardware(); SwoEnable(); LogInit(LOG_LEVEL_DEBUG); InitSwoEndpoint(); DMADRV_Init(); LeuartLineIOInit(&Main.IO); EpsInit(&Main.Hardware.I2C.Fallback); EPSPowerControlInitialize(&Main.PowerControlInterface); Main.Initialize(); InitializeTerminal(); SwoPutsOnChannel(0, "Hello I'm PW-SAT2 OBC\n"); SetupAntennas(); Main.Hardware.Pins.Led0.High(); Main.Hardware.Pins.Led1.High(); System::CreateTask(BlinkLed0, "Blink0", 512, NULL, TaskPriority::P1, NULL); System::CreateTask(ObcInitTask, "Init", 3_KB, &Main, TaskPriority::Highest, &Main.initTask); System::RunScheduler(); Main.Hardware.Pins.Led0.Toggle(); return 0; } <commit_msg>Implementing BURTC Interrupt Handler<commit_after>#include <cstdio> #include <cstring> #include <em_chip.h> #include <em_cmu.h> #include <em_dbg.h> #include <em_device.h> #include <em_emu.h> #include <em_gpio.h> #include <gsl/span> #include <em_system.h> #include <FreeRTOS.h> #include <FreeRTOSConfig.h> #include <task.h> #include "SwoEndpoint/SwoEndpoint.h" #include "adcs/adcs.h" #include "base/ecc.h" #include "base/os.h" #include "dmadrv.h" #include "em_burtc.h" #include "eps/eps.h" #include "fs/fs.h" #include "gpio/gpio.h" #include "i2c/i2c.h" #include "io_map.h" #include "leuart/leuart.h" #include "leuart/leuart.h" #include "logger/logger.h" #include "mission.h" #include "obc.h" #include "power_eps/power_eps.h" #include "storage/nand.h" #include "storage/nand_driver.h" #include "storage/storage.h" #include "swo/swo.h" #include "system.h" #include "terminal.h" using services::time::TimeProvider; using namespace std::chrono_literals; OBC Main; mission::ObcMission Mission(Main.timeProvider, Main.antennaDriver, false); const int __attribute__((used)) uxTopUsedPriority = configMAX_PRIORITIES; extern "C" void vApplicationStackOverflowHook(xTaskHandle* pxTask, signed char* pcTaskName) { UNREFERENCED_PARAMETER(pxTask); UNREFERENCED_PARAMETER(pcTaskName); } extern "C" void vApplicationIdleHook(void) { EMU_EnterEM1(); } void I2C0_IRQHandler(void) { Main.Hardware.I2C.Peripherals[0].Driver.IRQHandler(); } void I2C1_IRQHandler(void) { Main.Hardware.I2C.Peripherals[1].Driver.IRQHandler(); } OSSemaphoreHandle timerSemaphore; void BURTC_IRQHandler(void) { System::GiveSemaphore(timerSemaphore); } void configBURTC(void) { BURTC_Init_TypeDef burtcInit = BURTC_INIT_DEFAULT; burtcInit.mode = burtcModeEM4; burtcInit.clkSel = burtcClkSelLFRCO; burtcInit.clkDiv = 3; BURTC_CompareSet(0, 205); /* Set top value for comparator */ BURTC_IntEnable(BURTC_IF_COMP0); /* Enable compare interrupt flag */ NVIC_EnableIRQ(BURTC_IRQn); BURTC_Init(&burtcInit); } static void UpdateTimeProvider(void* param) { UNREFERENCED_PARAMETER(param); while (1) { System::TakeSemaphore(timerSemaphore, 50ms); Main.timeProvider.AdvanceTime(50ms); } } void configTimer(void) { configBURTC(); timerSemaphore = System::CreateBinarySemaphore(); System::CreateTask(UpdateTimeProvider, "UpdateTimeProvider", 512, NULL, TaskPriority::P1, NULL); } static void BlinkLed0(void* param) { UNREFERENCED_PARAMETER(param); while (1) { Main.Hardware.Pins.Led0.Toggle(); vTaskDelay(1000 / portTICK_PERIOD_MS); } } static void SmartWaitTask(void* param) { UNREFERENCED_PARAMETER(param); LOG(LOG_LEVEL_DEBUG, "Wait start"); while (1) { Main.timeProvider.LongDelay(10min); LOG(LOG_LEVEL_DEBUG, "After wait"); } } static void InitSwoEndpoint(void) { void* swoEndpointHandle = SwoEndpointInit(); const bool result = LogAddEndpoint(SwoGetEndpoint(swoEndpointHandle), swoEndpointHandle, LOG_LEVEL_TRACE); if (!result) { SwoPutsOnChannel(0, "Unable to attach swo endpoint to logger. "); } } static void ClearState(OBC* obc) { if (obc->Hardware.Pins.SysClear.Input() == false) { LOG(LOG_LEVEL_WARNING, "Clearing state on startup"); if (OS_RESULT_FAILED(obc->Storage.ClearStorage())) { LOG(LOG_LEVEL_ERROR, "Clearing state failed"); } LOG(LOG_LEVEL_INFO, "All files removed"); } } static void SetupAntennas(void) { AntennaMiniportInitialize(&Main.antennaMiniport); AntennaDriverInitialize(&Main.antennaDriver, &Main.antennaMiniport, &Main.Hardware.I2C.Buses.Bus, &Main.Hardware.I2C.Buses.Payload); } static void ObcInitTask(void* param) { auto obc = static_cast<OBC*>(param); obc->PostStartInitialization(); ClearState(obc); if (!obc->timeProvider.Initialize(nullptr, nullptr)) { LOG(LOG_LEVEL_ERROR, "Unable to initialize persistent timer. "); } if (OS_RESULT_FAILED(Main.antennaDriver.HardReset(&Main.antennaDriver))) { LOG(LOG_LEVEL_ERROR, "Unable to reset both antenna controllers. "); } if (!obc->Communication.CommDriver.Restart()) { LOG(LOG_LEVEL_ERROR, "Unable to restart comm"); } InitializeADCS(&obc->adcs); Mission.Initialize(); System::CreateTask(SmartWaitTask, "SmartWait", 512, NULL, TaskPriority::P1, NULL); LOG(LOG_LEVEL_INFO, "Intialized"); Main.initialized = true; System::SuspendTask(NULL); } void SetupHardware(void) { CMU_ClockEnable(cmuClock_GPIO, true); CMU_ClockEnable(cmuClock_DMA, true); CMU_ClockSelectSet(cmuClock_LFA, cmuSelect_HFCLKLE); CMU_ClockSelectSet(cmuClock_LFB, cmuSelect_HFCLKLE); } extern "C" void __libc_init_array(void); int main(void) { memset(&Main, 0, sizeof(Main)); __libc_init_array(); CHIP_Init(); SetupHardware(); SwoEnable(); LogInit(LOG_LEVEL_DEBUG); InitSwoEndpoint(); DMADRV_Init(); LeuartLineIOInit(&Main.IO); EpsInit(&Main.Hardware.I2C.Fallback); EPSPowerControlInitialize(&Main.PowerControlInterface); Main.Initialize(); InitializeTerminal(); SwoPutsOnChannel(0, "Hello I'm PW-SAT2 OBC\n"); SetupAntennas(); Main.Hardware.Pins.Led0.High(); Main.Hardware.Pins.Led1.High(); configTimer(); System::CreateTask(BlinkLed0, "Blink0", 512, NULL, TaskPriority::P1, NULL); System::CreateTask(ObcInitTask, "Init", 3_KB, &Main, TaskPriority::Highest, &Main.initTask); System::RunScheduler(); Main.Hardware.Pins.Led0.Toggle(); return 0; } <|endoftext|>
<commit_before>a971dd8c-35ca-11e5-a28d-6c40088e03e4<commit_msg>a97bbc3a-35ca-11e5-8933-6c40088e03e4<commit_after>a97bbc3a-35ca-11e5-8933-6c40088e03e4<|endoftext|>
<commit_before>/* This file is part of VROOM. Copyright (c) 2015-2021, Julien Coupey. All rights reserved (see LICENSE). */ #include <fstream> #include <iostream> #include <sstream> #ifndef _WIN32 #include <unistd.h> #endif #if USE_LIBOSRM #include "osrm/exception.hpp" #endif #include "../include/cxxopts/include/cxxopts.hpp" #include "problems/vrp.h" #include "structures/cl_args.h" #include "utils/helpers.h" #include "utils/input_parser.h" #include "utils/output_json.h" #include "utils/version.h" int main(int argc, char** argv) { vroom::io::CLArgs cl_args; std::string host_arg; std::string port_arg; std::string router_arg; std::string limit_arg; std::string nb_threads_arg; std::vector<std::string> heuristic_params_arg; // clang-format off cxxopts::Options options( "vroom", "VROOM Copyright (C) 2015-2021, Julien Coupey\n" "Version: " + vroom::get_version() + "\n" "A command-line utility to solve complex vehicle routing problems." ); options .set_width(80) .set_tab_expansion() .add_options("main_group") ("h,help", "Print this help message.") ("v,version", "Print the version of this software.") ("a,host", "The host for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":0.0.0.0'", cxxopts::value<std::string>(host_arg)->default_value("car:0.0.0.0")) ("c,choose-eta", "Choose ETA for custom routes and report violations.", cxxopts::value<bool>(cl_args.check)->default_value("false")) ("g,geometry", "Add detailed route geometry and indicators", cxxopts::value<bool>(cl_args.geometry)->default_value("false")) ("i,input-file", "Read input from 'input-file' rather than from stdin", cxxopts::value<std::string>(cl_args.input_file)) ("l,limit", "Stop solving process after 'limit' seconds", cxxopts::value<std::string>(limit_arg)->default_value("")) ("o,output", "Output file name", cxxopts::value<std::string>(cl_args.output_file)) ("p,port", "The host port for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":5000'", cxxopts::value<std::string>(port_arg)->default_value("car:5000")) ("r,router", "osrm, libosrm, ors or valhalla", cxxopts::value<std::string>(router_arg)->default_value("osrm")) ("t,threads", "Number of threads to use", cxxopts::value<unsigned>(cl_args.nb_threads)->default_value("4")) ("x,explore", "Exploration level to use (0..5)", cxxopts::value<unsigned>(cl_args.exploration_level)->default_value("5")); // we don't want to print debug args on --help options.add_options("debug_group") ("e,heuristic-param", "Heuristic parameter, useful for debugging", cxxopts::value<std::vector<std::string>>(heuristic_params_arg)); // clang-format on auto parsed_args = options.parse(argc, argv); if (parsed_args.count("help")) { std::cout << options.help({"main_group"}) << "\n"; exit(0); } if (parsed_args.count("version")) { std::cout << "vroom " << vroom::get_version() << "\n"; exit(0); } // parse and update some params vroom::io::update_host(cl_args.servers, host_arg); vroom::io::update_port(cl_args.servers, port_arg); if (!limit_arg.empty()) { // Internally timeout is in milliseconds. cl_args.timeout = 1000 * std::stof(limit_arg); } cl_args.exploration_level = std::min(cl_args.exploration_level, cl_args.max_exploration_level); // Determine routing engine (defaults to ROUTER::OSRM). if (router_arg == "libosrm") { cl_args.router = vroom::ROUTER::LIBOSRM; } else if (router_arg == "ors") { cl_args.router = vroom::ROUTER::ORS; } else if (router_arg == "valhalla") { cl_args.router = vroom::ROUTER::VALHALLA; } else if (!router_arg.empty() and router_arg != "osrm") { auto error_code = vroom::utils::get_code(vroom::ERROR::INPUT); std::string message = "Invalid routing engine: " + router_arg + "."; std::cerr << "[Error] " << message << std::endl; vroom::io::write_to_json({error_code, message}, false, cl_args.output_file); exit(error_code); } try { // Force heuristic parameters from the command-line, useful for // debugging. std::transform(heuristic_params_arg.begin(), heuristic_params_arg.end(), std::back_inserter(cl_args.h_params), [](const auto& str_param) { return vroom::utils::str_to_heuristic_param(str_param); }); } catch (const vroom::Exception& e) { auto error_code = vroom::utils::get_code(e.error); std::cerr << "[Error] " << e.message << std::endl; vroom::io::write_to_json({error_code, e.message}, false, cl_args.output_file); exit(error_code); } // Read input problem if (optind == argc) { std::stringstream buffer; if (cl_args.input_file.empty()) { // Getting input from stdin. buffer << std::cin.rdbuf(); } else { // Getting input from provided file. std::ifstream ifs(cl_args.input_file); buffer << ifs.rdbuf(); } cl_args.input = buffer.str(); } else { // Getting input from command-line. cl_args.input = argv[optind]; } try { // Build problem. vroom::Input problem_instance = vroom::io::parse(cl_args); vroom::Solution sol = (cl_args.check) ? problem_instance.check(cl_args.nb_threads) : problem_instance.solve(cl_args.exploration_level, cl_args.nb_threads, cl_args.timeout, cl_args.h_params); // Write solution. vroom::io::write_to_json(sol, cl_args.geometry, cl_args.output_file); } catch (const vroom::Exception& e) { auto error_code = vroom::utils::get_code(e.error); std::cerr << "[Error] " << e.message << std::endl; vroom::io::write_to_json({error_code, e.message}, false, cl_args.output_file); exit(error_code); } #if USE_LIBOSRM catch (const osrm::exception& e) { // In case of an unhandled routing error. auto error_code = vroom::utils::get_code(vroom::ERROR::ROUTING); auto message = "Routing problem: " + std::string(e.what()); std::cerr << "[Error] " << message << std::endl; vroom::io::write_to_json({error_code, message}, false, cl_args.output_file); exit(error_code); } #endif catch (const std::exception& e) { // In case of an unhandled internal error. auto error_code = vroom::utils::get_code(vroom::ERROR::INTERNAL); std::cerr << "[Error] " << e.what() << std::endl; vroom::io::write_to_json({error_code, e.what()}, false, cl_args.output_file); exit(error_code); } return 0; } <commit_msg>add positional arg; parse stdin, from file or from inline json; hide debug arg(s) from help output<commit_after>/* This file is part of VROOM. Copyright (c) 2015-2021, Julien Coupey. All rights reserved (see LICENSE). */ #include <fstream> #include <iostream> #include <sstream> #ifndef _WIN32 #include <unistd.h> #endif #if USE_LIBOSRM #include "osrm/exception.hpp" #endif #include "../include/cxxopts/include/cxxopts.hpp" #include "problems/vrp.h" #include "structures/cl_args.h" #include "utils/helpers.h" #include "utils/input_parser.h" #include "utils/output_json.h" #include "utils/version.h" int main(int argc, char** argv) { vroom::io::CLArgs cl_args; std::string host_arg; std::string port_arg; std::string router_arg; std::string limit_arg; std::string nb_threads_arg; std::vector<std::string> heuristic_params_arg; // clang-format off cxxopts::Options options( "vroom", "VROOM Copyright (C) 2015-2021, Julien Coupey\n" "Version: " + vroom::get_version() + "\n\n" "A command-line utility to solve complex vehicle routing problems.\n" ); options .set_width(80) .set_tab_expansion() .add_options("main_group") ("h,help", "Print this help message.") ("v,version", "Print the version of this software.") ("a,host", "The host for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":0.0.0.0'", cxxopts::value<std::string>(host_arg)->default_value("car:0.0.0.0")) ("c,choose-eta", "Choose ETA for custom routes and report violations.", cxxopts::value<bool>(cl_args.check)->default_value("false")) ("g,geometry", "Add detailed route geometry and indicators", cxxopts::value<bool>(cl_args.geometry)->default_value("false")) ("i,input-file", "Read input from 'input-file' rather than from stdin", cxxopts::value<std::string>(cl_args.input_file)) ("l,limit", "Stop solving process after 'limit' seconds", cxxopts::value<std::string>(limit_arg)->default_value("")) ("o,output", "Output file name", cxxopts::value<std::string>(cl_args.output_file)) ("p,port", "The host port for the routing profile, e.g. '" + vroom::DEFAULT_PROFILE + ":5000'", cxxopts::value<std::string>(port_arg)->default_value("car:5000")) ("r,router", "osrm, libosrm, ors or valhalla", cxxopts::value<std::string>(router_arg)->default_value("osrm")) ("t,threads", "Number of threads to use", cxxopts::value<unsigned>(cl_args.nb_threads)->default_value("4")) ("x,explore", "Exploration level to use (0..5)", cxxopts::value<unsigned>(cl_args.exploration_level)->default_value("5")) ("input", "optional input positional arg", cxxopts::value<std::string>(cl_args.input)); // we don't want to print debug args on --help options.add_options("debug_group") ("e,heuristic-param", "Heuristic parameter", cxxopts::value<std::vector<std::string>>(heuristic_params_arg)); // clang-format on options.parse_positional({"input"}); options.positional_help("OPTIONAL INLINE JSON"); auto parsed_args = options.parse(argc, argv); if (parsed_args.count("help")) { std::cout << options.help({"main_group"}) << "\n"; exit(0); } if (parsed_args.count("version")) { std::cout << "vroom " << vroom::get_version() << "\n"; exit(0); } // parse and update some params vroom::io::update_host(cl_args.servers, host_arg); vroom::io::update_port(cl_args.servers, port_arg); if (!limit_arg.empty()) { // Internally timeout is in milliseconds. cl_args.timeout = 1000 * std::stof(limit_arg); } cl_args.exploration_level = std::min(cl_args.exploration_level, cl_args.max_exploration_level); // Determine routing engine (defaults to ROUTER::OSRM). if (router_arg == "libosrm") { cl_args.router = vroom::ROUTER::LIBOSRM; } else if (router_arg == "ors") { cl_args.router = vroom::ROUTER::ORS; } else if (router_arg == "valhalla") { cl_args.router = vroom::ROUTER::VALHALLA; } else if (!router_arg.empty() and router_arg != "osrm") { auto error_code = vroom::utils::get_code(vroom::ERROR::INPUT); std::string message = "Invalid routing engine: " + router_arg + "."; std::cerr << "[Error] " << message << std::endl; vroom::io::write_to_json({error_code, message}, false, cl_args.output_file); exit(error_code); } try { // Force heuristic parameters from the command-line, useful for // debugging. std::transform(heuristic_params_arg.begin(), heuristic_params_arg.end(), std::back_inserter(cl_args.h_params), [](const auto& str_param) { return vroom::utils::str_to_heuristic_param(str_param); }); } catch (const vroom::Exception& e) { auto error_code = vroom::utils::get_code(e.error); std::cerr << "[Error] " << e.message << std::endl; vroom::io::write_to_json({error_code, e.message}, false, cl_args.output_file); exit(error_code); } // Read input problem if (cl_args.input.empty()) { std::stringstream buffer; if (!cl_args.input_file.empty()) { std::ifstream ifs(cl_args.input_file); buffer << ifs.rdbuf(); } else { buffer << std::cin.rdbuf(); } cl_args.input = buffer.str(); } try { // Build problem. vroom::Input problem_instance = vroom::io::parse(cl_args); vroom::Solution sol = (cl_args.check) ? problem_instance.check(cl_args.nb_threads) : problem_instance.solve(cl_args.exploration_level, cl_args.nb_threads, cl_args.timeout, cl_args.h_params); // Write solution. vroom::io::write_to_json(sol, cl_args.geometry, cl_args.output_file); } catch (const vroom::Exception& e) { auto error_code = vroom::utils::get_code(e.error); std::cerr << "[Error] " << e.message << std::endl; vroom::io::write_to_json({error_code, e.message}, false, cl_args.output_file); exit(error_code); } #if USE_LIBOSRM catch (const osrm::exception& e) { // In case of an unhandled routing error. auto error_code = vroom::utils::get_code(vroom::ERROR::ROUTING); auto message = "Routing problem: " + std::string(e.what()); std::cerr << "[Error] " << message << std::endl; vroom::io::write_to_json({error_code, message}, false, cl_args.output_file); exit(error_code); } #endif catch (const std::exception& e) { // In case of an unhandled internal error. auto error_code = vroom::utils::get_code(vroom::ERROR::INTERNAL); std::cerr << "[Error] " << e.what() << std::endl; vroom::io::write_to_json({error_code, e.what()}, false, cl_args.output_file); exit(error_code); } return 0; } <|endoftext|>
<commit_before>dd9480dc-585a-11e5-8711-6c40088e03e4<commit_msg>dd9b4022-585a-11e5-ae8a-6c40088e03e4<commit_after>dd9b4022-585a-11e5-ae8a-6c40088e03e4<|endoftext|>
<commit_before>void asignacion1() { // OMIT int a,b; // a:?, b:? a = 10; // a:10, b:? b = 4; // a:10, b:4 a = b; // a:4, b:4 b = 7; // a:4, b:7 printf("a:%d\tb:%d\n",a,b); } // OMIT void asignacion2() { // OMIT int m,n,p; // m:?, n:?, p:? // p = 5; // m:?, n:?, p:5 // n = p; // m:?, n:5, p:5 // m = n; // m:5, n:5, p:5 m = n = p = 5; } // OMIT void asignacion3() { // OMIT } // OMIT <commit_msg>c++ operators/asignacion.cpp - tercer ejemplo<commit_after>void asignacion1() { // OMIT int a,b; // a:?, b:? a = 10; // a:10, b:? b = 4; // a:10, b:4 a = b; // a:4, b:4 b = 7; // a:4, b:7 printf("a:%d\tb:%d\n",a,b); } // OMIT void asignacion2() { // OMIT int m,n,p; // m:?, n:?, p:? // p = 5; // m:?, n:?, p:5 // n = p; // m:?, n:5, p:5 // m = n; // m:5, n:5, p:5 m = n = p = 5; printf("m:%d\tn:%d\tp:%d\n",m,n,p); } // OMIT void asignacion3() { // OMIT int x,y; // x:?, y:? // x = 5; // x:5, y:? // y = 2 + x; // x:5, y:7 y = 2 + (x = 5); printf("x:%d\ty:%d\n",x,y); } // OMIT <|endoftext|>
<commit_before>/** * Copyright (c) 2016-2018 mvs developers * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <functional> #include <memory> #include <string> #include <array> #include <metaverse/explorer/command.hpp> #include <metaverse/explorer/dispatch.hpp> #include <metaverse/explorer/extensions/command_extension.hpp> #include <metaverse/explorer/extensions/command_extension_func.hpp> #include <metaverse/explorer/extensions/commands/shutdown.hpp> #include <metaverse/explorer/extensions/commands/stopmining.hpp> #include <metaverse/explorer/extensions/commands/startmining.hpp> #include <metaverse/explorer/extensions/commands/getinfo.hpp> #include <metaverse/explorer/extensions/commands/getheight.hpp> #include <metaverse/explorer/extensions/commands/getpeerinfo.hpp> #include <metaverse/explorer/extensions/commands/getaddressetp.hpp> #include <metaverse/explorer/extensions/commands/addnode.hpp> #include <metaverse/explorer/extensions/commands/getmininginfo.hpp> #include <metaverse/explorer/extensions/commands/getblockheader.hpp> #include <metaverse/explorer/extensions/commands/fetchheaderext.hpp> #include <metaverse/explorer/extensions/commands/gettx.hpp> #include <metaverse/explorer/extensions/commands/dumpkeyfile.hpp> #include <metaverse/explorer/extensions/commands/importkeyfile.hpp> #include <metaverse/explorer/extensions/commands/importaccount.hpp> #include <metaverse/explorer/extensions/commands/getnewaccount.hpp> #include <metaverse/explorer/extensions/commands/getaccount.hpp> #include <metaverse/explorer/extensions/commands/deleteaccount.hpp> #include <metaverse/explorer/extensions/commands/listaddresses.hpp> #include <metaverse/explorer/extensions/commands/getnewaddress.hpp> #include <metaverse/explorer/extensions/commands/getblock.hpp> #include <metaverse/explorer/extensions/commands/validateaddress.hpp> #include <metaverse/explorer/extensions/commands/listbalances.hpp> #include <metaverse/explorer/extensions/commands/getbalance.hpp> #include <metaverse/explorer/extensions/commands/listtxs.hpp> #include <metaverse/explorer/extensions/commands/deposit.hpp> #include <metaverse/explorer/extensions/commands/listassets.hpp> #include <metaverse/explorer/extensions/commands/getasset.hpp> #include <metaverse/explorer/extensions/commands/secondaryissue.hpp> #include <metaverse/explorer/extensions/commands/getaddressasset.hpp> #include <metaverse/explorer/extensions/commands/getaccountasset.hpp> #include <metaverse/explorer/extensions/commands/getassetview.hpp> #include <metaverse/explorer/extensions/commands/createasset.hpp> #include <metaverse/explorer/extensions/commands/registermit.hpp> #include <metaverse/explorer/extensions/commands/transfermit.hpp> #include <metaverse/explorer/extensions/commands/listmits.hpp> #include <metaverse/explorer/extensions/commands/getmit.hpp> #include <metaverse/explorer/extensions/commands/registerdid.hpp> #include <metaverse/explorer/extensions/commands/send.hpp> #include <metaverse/explorer/extensions/commands/sendfrom.hpp> #include <metaverse/explorer/extensions/commands/sendmore.hpp> #include <metaverse/explorer/extensions/commands/sendasset.hpp> #include <metaverse/explorer/extensions/commands/sendassetfrom.hpp> #include <metaverse/explorer/extensions/commands/swaptoken.hpp> #include <metaverse/explorer/extensions/commands/listdids.hpp> #include <metaverse/explorer/extensions/commands/deletelocalasset.hpp> #include <metaverse/explorer/extensions/commands/issue.hpp> #include <metaverse/explorer/extensions/commands/burn.hpp> #include <metaverse/explorer/extensions/commands/transfercert.hpp> #include <metaverse/explorer/extensions/commands/issuecert.hpp> #include <metaverse/explorer/extensions/commands/getwork.hpp> #include <metaverse/explorer/extensions/commands/submitwork.hpp> #include <metaverse/explorer/extensions/commands/setminingaccount.hpp> #include <metaverse/explorer/extensions/commands/changepasswd.hpp> #include <metaverse/explorer/extensions/commands/getmemorypool.hpp> #include <metaverse/explorer/extensions/commands/createmultisigtx.hpp> #include <metaverse/explorer/extensions/commands/createrawtx.hpp> #include <metaverse/explorer/extensions/commands/decoderawtx.hpp> #include <metaverse/explorer/extensions/commands/deletemultisig.hpp> #include <metaverse/explorer/extensions/commands/getnewmultisig.hpp> #include <metaverse/explorer/extensions/commands/getpublickey.hpp> #include <metaverse/explorer/extensions/commands/listmultisig.hpp> #include <metaverse/explorer/extensions/commands/sendrawtx.hpp> #include <metaverse/explorer/extensions/commands/signmultisigtx.hpp> #include <metaverse/explorer/extensions/commands/signrawtx.hpp> #include <metaverse/explorer/extensions/commands/didchangeaddress.hpp> #include <metaverse/explorer/extensions/commands/getdid.hpp> namespace libbitcoin { namespace explorer { void broadcast_extension(const function<void(shared_ptr<command>)> func, std::ostream& os) { using namespace std; using namespace commands; os <<"\r\n"; // account func(make_shared<getnewaccount>()); func(make_shared<getaccount>()); func(make_shared<deleteaccount>()); func(make_shared<importaccount>()); func(make_shared<changepasswd>()); func(make_shared<getnewaddress>()); func(make_shared<validateaddress>()); func(make_shared<listaddresses>()); func(make_shared<dumpkeyfile>()); func(make_shared<importkeyfile>()); os <<"\r\n"; // system func(make_shared<shutdown>()); func(make_shared<getinfo>()); func(make_shared<addnode>()); func(make_shared<getpeerinfo>()); // miming func(make_shared<startmining>()); func(make_shared<stopmining>()); func(make_shared<getmininginfo>()); func(make_shared<setminingaccount>()); func(make_shared<getwork>()); func(make_shared<submitwork>()); func(make_shared<getmemorypool>()); os <<"\r\n"; // block & tx func(make_shared<getheight>()); func(make_shared<getblock>()); func(make_shared<getblockheader>()); func(make_shared<fetchheaderext>()); func(make_shared<gettx>()); func(make_shared<listtxs>()); // raw tx func(make_shared<createrawtx>()); func(make_shared<decoderawtx>()); func(make_shared<signrawtx>()); func(make_shared<sendrawtx>()); os <<"\r\n"; // multi-sig func(make_shared<getpublickey>()); func(make_shared<createmultisigtx>()); func(make_shared<getnewmultisig>()); func(make_shared<listmultisig>()); func(make_shared<deletemultisig>()); func(make_shared<signmultisigtx>()); os <<"\r\n"; // etp func(make_shared<send>()); func(make_shared<sendmore>()); func(make_shared<sendfrom>()); func(make_shared<deposit>()); func(make_shared<listbalances>()); func(make_shared<getbalance>()); func(make_shared<getaddressetp>()); os <<"\r\n"; // asset func(make_shared<createasset>()); func(make_shared<deletelocalasset>()); func(make_shared<issue>()); func(make_shared<secondaryissue>()); func(make_shared<sendasset>()); func(make_shared<sendassetfrom>()); func(make_shared<listassets>()); func(make_shared<getasset>()); func(make_shared<getaccountasset>()); func(make_shared<getassetview>()); func(make_shared<getaddressasset>()); func(make_shared<burn>()); func(make_shared<swaptoken>()); os <<"\r\n"; // cert func(make_shared<issuecert>()); func(make_shared<transfercert>()); os <<"\r\n"; // mit func(make_shared<registermit>()); func(make_shared<transfermit>()); func(make_shared<listmits>()); func(make_shared<getmit>()); os <<"\r\n"; //did func(make_shared<registerdid>()); func(make_shared<didchangeaddress>()); func(make_shared<listdids>()); func(make_shared<getdid>()); } shared_ptr<command> find_extension(const string& symbol) { using namespace std; using namespace commands; // account if (symbol == getnewaccount::symbol()) return make_shared<getnewaccount>(); if (symbol == getaccount::symbol()) return make_shared<getaccount>(); if (symbol == deleteaccount::symbol()) return make_shared<deleteaccount>(); if (symbol == changepasswd::symbol()) return make_shared<changepasswd>(); if (symbol == validateaddress::symbol()) return make_shared<validateaddress>(); if (symbol == getnewaddress::symbol()) return make_shared<getnewaddress>(); if (symbol == listaddresses::symbol()) return make_shared<listaddresses>(); if (symbol == importaccount::symbol()) return make_shared<importaccount>(); if (symbol == dumpkeyfile::symbol() || symbol == "exportaccountasfile") return make_shared<dumpkeyfile>(); if (symbol == importkeyfile::symbol() || symbol == "importaccountfromfile") return make_shared<importkeyfile>(); // system if (symbol == shutdown::symbol()) return make_shared<shutdown>(); if (symbol == getinfo::symbol()) return make_shared<getinfo>(); if (symbol == addnode::symbol()) return make_shared<addnode>(); if (symbol == getpeerinfo::symbol()) return make_shared<getpeerinfo>(); // mining if (symbol == stopmining::symbol() || symbol == "stop") return make_shared<stopmining>(); if (symbol == startmining::symbol() || symbol == "start") return make_shared<startmining>(); if (symbol == setminingaccount::symbol()) return make_shared<setminingaccount>(); if (symbol == getmininginfo::symbol()) return make_shared<getmininginfo>(); if ((symbol == getwork::symbol()) || (symbol == "eth_getWork")) return make_shared<getwork>(); if ((symbol == submitwork::symbol()) || ( symbol == "eth_submitWork")) return make_shared<submitwork>(); if (symbol == getmemorypool::symbol()) return make_shared<getmemorypool>(); // block & tx if (symbol == getheight::symbol()) return make_shared<getheight>(); if (symbol == "fetch-height") return make_shared<getheight>(symbol); if (symbol == getblock::symbol()) return make_shared<getblock>(); if (symbol == "getbestblockhash") return make_shared<getblockheader>(symbol); if (symbol == getblockheader::symbol() || symbol == "fetch-header" || symbol == "getbestblockheader") return make_shared<getblockheader>(); if (symbol == fetchheaderext::symbol()) return make_shared<fetchheaderext>(); if (symbol == gettx::symbol() || symbol == "gettransaction") return make_shared<gettx>(); if (symbol == "fetch-tx") return make_shared<gettx>(symbol); if (symbol == listtxs::symbol()) return make_shared<listtxs>(); // raw tx if (symbol == createrawtx::symbol()) return make_shared<createrawtx>(); if (symbol == decoderawtx::symbol()) return make_shared<decoderawtx>(); if (symbol == signrawtx::symbol()) return make_shared<signrawtx>(); if (symbol == sendrawtx::symbol()) return make_shared<sendrawtx>(); // multi-sig if (symbol == getpublickey::symbol()) return make_shared<getpublickey>(); if (symbol == getnewmultisig::symbol()) return make_shared<getnewmultisig>(); if (symbol == listmultisig::symbol()) return make_shared<listmultisig>(); if (symbol == deletemultisig::symbol()) return make_shared<deletemultisig>(); if (symbol == createmultisigtx::symbol()) return make_shared<createmultisigtx>(); if (symbol == signmultisigtx::symbol()) return make_shared<signmultisigtx>(); // etp if (symbol == listbalances::symbol()) return make_shared<listbalances>(); if (symbol == getbalance::symbol()) return make_shared<getbalance>(); if (symbol == getaddressetp::symbol() || symbol == "fetch-balance") return make_shared<getaddressetp>(); if (symbol == deposit::symbol()) return make_shared<deposit>(); if (symbol == send::symbol() || symbol == "didsend") return make_shared<send>(); if (symbol == sendmore::symbol() || symbol == "didsendmore") return make_shared<sendmore>(); if (symbol == sendfrom::symbol() || symbol == "didsendfrom") return make_shared<sendfrom>(); // asset if (symbol == createasset::symbol()) return make_shared<createasset>(); if (symbol == deletelocalasset::symbol() || symbol == "deleteasset" ) return make_shared<deletelocalasset>(); if (symbol == listassets::symbol()) return make_shared<listassets>(); if (symbol == getasset::symbol()) return make_shared<getasset>(); if (symbol == getaccountasset::symbol()) return make_shared<getaccountasset>(); if (symbol == getassetview::symbol()) return make_shared<getassetview>(); if (symbol == getaddressasset::symbol()) return make_shared<getaddressasset>(); if (symbol == issue::symbol()) return make_shared<issue>(); if (symbol == secondaryissue::symbol() || (symbol == "additionalissue") ) return make_shared<secondaryissue>(); if (symbol == sendasset::symbol() || symbol == "didsendasset") return make_shared<sendasset>(); if (symbol == sendassetfrom::symbol() || symbol == "didsendassetfrom") return make_shared<sendassetfrom>(); if (symbol == burn::symbol()) return make_shared<burn>(); if (symbol == swaptoken::symbol()) return make_shared<swaptoken>(); // cert if (symbol == transfercert::symbol()) return make_shared<transfercert>(); if (symbol == issuecert::symbol()) return make_shared<issuecert>(); // mit if (symbol == registermit::symbol()) return make_shared<registermit>(); if (symbol == transfermit::symbol()) return make_shared<transfermit>(); if (symbol == listmits::symbol()) return make_shared<listmits>(); if (symbol == getmit::symbol()) return make_shared<getmit>(); // did if (symbol == registerdid::symbol()) return make_shared<registerdid>(); if (symbol == didchangeaddress::symbol()) return make_shared<didchangeaddress>(); if (symbol == listdids::symbol()) return make_shared<listdids>(); if (symbol == getdid::symbol()) return make_shared<getdid>(); return nullptr; } std::string formerly_extension(const string& former) { return ""; } } // namespace explorer } // namespace libbitcoin <commit_msg>disable getassetview<commit_after>/** * Copyright (c) 2016-2018 mvs developers * * This file is part of metaverse-explorer. * * metaverse-explorer is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <functional> #include <memory> #include <string> #include <array> #include <metaverse/explorer/command.hpp> #include <metaverse/explorer/dispatch.hpp> #include <metaverse/explorer/extensions/command_extension.hpp> #include <metaverse/explorer/extensions/command_extension_func.hpp> #include <metaverse/explorer/extensions/commands/shutdown.hpp> #include <metaverse/explorer/extensions/commands/stopmining.hpp> #include <metaverse/explorer/extensions/commands/startmining.hpp> #include <metaverse/explorer/extensions/commands/getinfo.hpp> #include <metaverse/explorer/extensions/commands/getheight.hpp> #include <metaverse/explorer/extensions/commands/getpeerinfo.hpp> #include <metaverse/explorer/extensions/commands/getaddressetp.hpp> #include <metaverse/explorer/extensions/commands/addnode.hpp> #include <metaverse/explorer/extensions/commands/getmininginfo.hpp> #include <metaverse/explorer/extensions/commands/getblockheader.hpp> #include <metaverse/explorer/extensions/commands/fetchheaderext.hpp> #include <metaverse/explorer/extensions/commands/gettx.hpp> #include <metaverse/explorer/extensions/commands/dumpkeyfile.hpp> #include <metaverse/explorer/extensions/commands/importkeyfile.hpp> #include <metaverse/explorer/extensions/commands/importaccount.hpp> #include <metaverse/explorer/extensions/commands/getnewaccount.hpp> #include <metaverse/explorer/extensions/commands/getaccount.hpp> #include <metaverse/explorer/extensions/commands/deleteaccount.hpp> #include <metaverse/explorer/extensions/commands/listaddresses.hpp> #include <metaverse/explorer/extensions/commands/getnewaddress.hpp> #include <metaverse/explorer/extensions/commands/getblock.hpp> #include <metaverse/explorer/extensions/commands/validateaddress.hpp> #include <metaverse/explorer/extensions/commands/listbalances.hpp> #include <metaverse/explorer/extensions/commands/getbalance.hpp> #include <metaverse/explorer/extensions/commands/listtxs.hpp> #include <metaverse/explorer/extensions/commands/deposit.hpp> #include <metaverse/explorer/extensions/commands/listassets.hpp> #include <metaverse/explorer/extensions/commands/getasset.hpp> #include <metaverse/explorer/extensions/commands/secondaryissue.hpp> #include <metaverse/explorer/extensions/commands/getaddressasset.hpp> #include <metaverse/explorer/extensions/commands/getaccountasset.hpp> #include <metaverse/explorer/extensions/commands/getassetview.hpp> #include <metaverse/explorer/extensions/commands/createasset.hpp> #include <metaverse/explorer/extensions/commands/registermit.hpp> #include <metaverse/explorer/extensions/commands/transfermit.hpp> #include <metaverse/explorer/extensions/commands/listmits.hpp> #include <metaverse/explorer/extensions/commands/getmit.hpp> #include <metaverse/explorer/extensions/commands/registerdid.hpp> #include <metaverse/explorer/extensions/commands/send.hpp> #include <metaverse/explorer/extensions/commands/sendfrom.hpp> #include <metaverse/explorer/extensions/commands/sendmore.hpp> #include <metaverse/explorer/extensions/commands/sendasset.hpp> #include <metaverse/explorer/extensions/commands/sendassetfrom.hpp> #include <metaverse/explorer/extensions/commands/swaptoken.hpp> #include <metaverse/explorer/extensions/commands/listdids.hpp> #include <metaverse/explorer/extensions/commands/deletelocalasset.hpp> #include <metaverse/explorer/extensions/commands/issue.hpp> #include <metaverse/explorer/extensions/commands/burn.hpp> #include <metaverse/explorer/extensions/commands/transfercert.hpp> #include <metaverse/explorer/extensions/commands/issuecert.hpp> #include <metaverse/explorer/extensions/commands/getwork.hpp> #include <metaverse/explorer/extensions/commands/submitwork.hpp> #include <metaverse/explorer/extensions/commands/setminingaccount.hpp> #include <metaverse/explorer/extensions/commands/changepasswd.hpp> #include <metaverse/explorer/extensions/commands/getmemorypool.hpp> #include <metaverse/explorer/extensions/commands/createmultisigtx.hpp> #include <metaverse/explorer/extensions/commands/createrawtx.hpp> #include <metaverse/explorer/extensions/commands/decoderawtx.hpp> #include <metaverse/explorer/extensions/commands/deletemultisig.hpp> #include <metaverse/explorer/extensions/commands/getnewmultisig.hpp> #include <metaverse/explorer/extensions/commands/getpublickey.hpp> #include <metaverse/explorer/extensions/commands/listmultisig.hpp> #include <metaverse/explorer/extensions/commands/sendrawtx.hpp> #include <metaverse/explorer/extensions/commands/signmultisigtx.hpp> #include <metaverse/explorer/extensions/commands/signrawtx.hpp> #include <metaverse/explorer/extensions/commands/didchangeaddress.hpp> #include <metaverse/explorer/extensions/commands/getdid.hpp> namespace libbitcoin { namespace explorer { void broadcast_extension(const function<void(shared_ptr<command>)> func, std::ostream& os) { using namespace std; using namespace commands; os <<"\r\n"; // account func(make_shared<getnewaccount>()); func(make_shared<getaccount>()); func(make_shared<deleteaccount>()); func(make_shared<importaccount>()); func(make_shared<changepasswd>()); func(make_shared<getnewaddress>()); func(make_shared<validateaddress>()); func(make_shared<listaddresses>()); func(make_shared<dumpkeyfile>()); func(make_shared<importkeyfile>()); os <<"\r\n"; // system func(make_shared<shutdown>()); func(make_shared<getinfo>()); func(make_shared<addnode>()); func(make_shared<getpeerinfo>()); // miming func(make_shared<startmining>()); func(make_shared<stopmining>()); func(make_shared<getmininginfo>()); func(make_shared<setminingaccount>()); func(make_shared<getwork>()); func(make_shared<submitwork>()); func(make_shared<getmemorypool>()); os <<"\r\n"; // block & tx func(make_shared<getheight>()); func(make_shared<getblock>()); func(make_shared<getblockheader>()); func(make_shared<fetchheaderext>()); func(make_shared<gettx>()); func(make_shared<listtxs>()); // raw tx func(make_shared<createrawtx>()); func(make_shared<decoderawtx>()); func(make_shared<signrawtx>()); func(make_shared<sendrawtx>()); os <<"\r\n"; // multi-sig func(make_shared<getpublickey>()); func(make_shared<createmultisigtx>()); func(make_shared<getnewmultisig>()); func(make_shared<listmultisig>()); func(make_shared<deletemultisig>()); func(make_shared<signmultisigtx>()); os <<"\r\n"; // etp func(make_shared<send>()); func(make_shared<sendmore>()); func(make_shared<sendfrom>()); func(make_shared<deposit>()); func(make_shared<listbalances>()); func(make_shared<getbalance>()); func(make_shared<getaddressetp>()); os <<"\r\n"; // asset func(make_shared<createasset>()); func(make_shared<deletelocalasset>()); func(make_shared<issue>()); func(make_shared<secondaryissue>()); func(make_shared<sendasset>()); func(make_shared<sendassetfrom>()); func(make_shared<listassets>()); func(make_shared<getasset>()); func(make_shared<getaccountasset>()); // func(make_shared<getassetview>()); func(make_shared<getaddressasset>()); func(make_shared<burn>()); func(make_shared<swaptoken>()); os <<"\r\n"; // cert func(make_shared<issuecert>()); func(make_shared<transfercert>()); os <<"\r\n"; // mit func(make_shared<registermit>()); func(make_shared<transfermit>()); func(make_shared<listmits>()); func(make_shared<getmit>()); os <<"\r\n"; //did func(make_shared<registerdid>()); func(make_shared<didchangeaddress>()); func(make_shared<listdids>()); func(make_shared<getdid>()); } shared_ptr<command> find_extension(const string& symbol) { using namespace std; using namespace commands; // account if (symbol == getnewaccount::symbol()) return make_shared<getnewaccount>(); if (symbol == getaccount::symbol()) return make_shared<getaccount>(); if (symbol == deleteaccount::symbol()) return make_shared<deleteaccount>(); if (symbol == changepasswd::symbol()) return make_shared<changepasswd>(); if (symbol == validateaddress::symbol()) return make_shared<validateaddress>(); if (symbol == getnewaddress::symbol()) return make_shared<getnewaddress>(); if (symbol == listaddresses::symbol()) return make_shared<listaddresses>(); if (symbol == importaccount::symbol()) return make_shared<importaccount>(); if (symbol == dumpkeyfile::symbol() || symbol == "exportaccountasfile") return make_shared<dumpkeyfile>(); if (symbol == importkeyfile::symbol() || symbol == "importaccountfromfile") return make_shared<importkeyfile>(); // system if (symbol == shutdown::symbol()) return make_shared<shutdown>(); if (symbol == getinfo::symbol()) return make_shared<getinfo>(); if (symbol == addnode::symbol()) return make_shared<addnode>(); if (symbol == getpeerinfo::symbol()) return make_shared<getpeerinfo>(); // mining if (symbol == stopmining::symbol() || symbol == "stop") return make_shared<stopmining>(); if (symbol == startmining::symbol() || symbol == "start") return make_shared<startmining>(); if (symbol == setminingaccount::symbol()) return make_shared<setminingaccount>(); if (symbol == getmininginfo::symbol()) return make_shared<getmininginfo>(); if ((symbol == getwork::symbol()) || (symbol == "eth_getWork")) return make_shared<getwork>(); if ((symbol == submitwork::symbol()) || ( symbol == "eth_submitWork")) return make_shared<submitwork>(); if (symbol == getmemorypool::symbol()) return make_shared<getmemorypool>(); // block & tx if (symbol == getheight::symbol()) return make_shared<getheight>(); if (symbol == "fetch-height") return make_shared<getheight>(symbol); if (symbol == getblock::symbol()) return make_shared<getblock>(); if (symbol == "getbestblockhash") return make_shared<getblockheader>(symbol); if (symbol == getblockheader::symbol() || symbol == "fetch-header" || symbol == "getbestblockheader") return make_shared<getblockheader>(); if (symbol == fetchheaderext::symbol()) return make_shared<fetchheaderext>(); if (symbol == gettx::symbol() || symbol == "gettransaction") return make_shared<gettx>(); if (symbol == "fetch-tx") return make_shared<gettx>(symbol); if (symbol == listtxs::symbol()) return make_shared<listtxs>(); // raw tx if (symbol == createrawtx::symbol()) return make_shared<createrawtx>(); if (symbol == decoderawtx::symbol()) return make_shared<decoderawtx>(); if (symbol == signrawtx::symbol()) return make_shared<signrawtx>(); if (symbol == sendrawtx::symbol()) return make_shared<sendrawtx>(); // multi-sig if (symbol == getpublickey::symbol()) return make_shared<getpublickey>(); if (symbol == getnewmultisig::symbol()) return make_shared<getnewmultisig>(); if (symbol == listmultisig::symbol()) return make_shared<listmultisig>(); if (symbol == deletemultisig::symbol()) return make_shared<deletemultisig>(); if (symbol == createmultisigtx::symbol()) return make_shared<createmultisigtx>(); if (symbol == signmultisigtx::symbol()) return make_shared<signmultisigtx>(); // etp if (symbol == listbalances::symbol()) return make_shared<listbalances>(); if (symbol == getbalance::symbol()) return make_shared<getbalance>(); if (symbol == getaddressetp::symbol() || symbol == "fetch-balance") return make_shared<getaddressetp>(); if (symbol == deposit::symbol()) return make_shared<deposit>(); if (symbol == send::symbol() || symbol == "didsend") return make_shared<send>(); if (symbol == sendmore::symbol() || symbol == "didsendmore") return make_shared<sendmore>(); if (symbol == sendfrom::symbol() || symbol == "didsendfrom") return make_shared<sendfrom>(); // asset if (symbol == createasset::symbol()) return make_shared<createasset>(); if (symbol == deletelocalasset::symbol() || symbol == "deleteasset" ) return make_shared<deletelocalasset>(); if (symbol == listassets::symbol()) return make_shared<listassets>(); if (symbol == getasset::symbol()) return make_shared<getasset>(); if (symbol == getaccountasset::symbol()) return make_shared<getaccountasset>(); // if (symbol == getassetview::symbol()) // return make_shared<getassetview>(); if (symbol == getaddressasset::symbol()) return make_shared<getaddressasset>(); if (symbol == issue::symbol()) return make_shared<issue>(); if (symbol == secondaryissue::symbol() || (symbol == "additionalissue") ) return make_shared<secondaryissue>(); if (symbol == sendasset::symbol() || symbol == "didsendasset") return make_shared<sendasset>(); if (symbol == sendassetfrom::symbol() || symbol == "didsendassetfrom") return make_shared<sendassetfrom>(); if (symbol == burn::symbol()) return make_shared<burn>(); if (symbol == swaptoken::symbol()) return make_shared<swaptoken>(); // cert if (symbol == transfercert::symbol()) return make_shared<transfercert>(); if (symbol == issuecert::symbol()) return make_shared<issuecert>(); // mit if (symbol == registermit::symbol()) return make_shared<registermit>(); if (symbol == transfermit::symbol()) return make_shared<transfermit>(); if (symbol == listmits::symbol()) return make_shared<listmits>(); if (symbol == getmit::symbol()) return make_shared<getmit>(); // did if (symbol == registerdid::symbol()) return make_shared<registerdid>(); if (symbol == didchangeaddress::symbol()) return make_shared<didchangeaddress>(); if (symbol == listdids::symbol()) return make_shared<listdids>(); if (symbol == getdid::symbol()) return make_shared<getdid>(); return nullptr; } std::string formerly_extension(const string& former) { return ""; } } // namespace explorer } // namespace libbitcoin <|endoftext|>
<commit_before>6d43afd4-2fa5-11e5-b64f-00012e3d3f12<commit_msg>6d455d86-2fa5-11e5-931f-00012e3d3f12<commit_after>6d455d86-2fa5-11e5-931f-00012e3d3f12<|endoftext|>
<commit_before>/** \file rss_subset_aggregator.cc * \brief Aggregates RSS feeds. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <map> #include <unordered_map> #include <unordered_set> #include <cinttypes> #include <cstring> #include "Compiler.h" #include "DbConnection.h" #include "DbResultSet.h" #include "EmailSender.h" #include "FileUtil.h" #include "HtmlUtil.h" #include "MiscUtil.h" #include "SqlUtil.h" #include "StringUtil.h" #include "SyndicationFormat.h" #include "Template.h" #include "TimeUtil.h" #include "UBTools.h" #include "VuFind.h" #include "XmlWriter.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage( "--mode=(email|rss_xml) (user_id|sender_email) subsystem_type\n" "If the mode is \"rss_xml\" a VuFind user_id needs to be specified, o/w an error email address should be provided."); } struct HarvestedRSSItem { SyndicationFormat::Item item_; std::string feed_title_; std::string website_url_; HarvestedRSSItem(const SyndicationFormat::Item item, const std::string &feed_title, const std::string &website_url) : item_(item), feed_title_(feed_title), website_url_(website_url) { } }; struct ChannelDesc { std::string title_; std::string link_; public: ChannelDesc(const std::string &title, const std::string &link): title_(title), link_(link) { } }; const std::map<std::string, ChannelDesc> subsystem_type_to_channel_desc_map = { { "relbib", ChannelDesc("RelBib RSS Aggregator", "https://relbib.de/") }, { "ixtheo", ChannelDesc("IxTheo RSS Aggregator", "https://ixtheo.de/") }, { "krimdok", ChannelDesc("KrimDok RSS Aggregator", "https://krimdok.uni-tuebingen.de/") }, }; std::string GetChannelDescEntry(const std::string &subsystem_type, const std::string &entry) { const auto subsystem_type_and_channel_desc(subsystem_type_to_channel_desc_map.find(subsystem_type)); if (subsystem_type_and_channel_desc == subsystem_type_to_channel_desc_map.cend()) LOG_ERROR("unknown subsystem type \"" + subsystem_type + "\"!"); if (entry == "title") return subsystem_type_and_channel_desc->second.title_; if (entry == "link") return subsystem_type_and_channel_desc->second.link_; LOG_ERROR("unknown entry name \"" + entry + "\"!"); } void WriteRSSFeedXMLOutput(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items, XmlWriter * const xml_writer) { xml_writer->openTag("rss", { { "version", "2.0" } }); xml_writer->openTag("channel"); xml_writer->writeTagsWithData("title", GetChannelDescEntry(subsystem_type, "title")); xml_writer->writeTagsWithData("link", GetChannelDescEntry(subsystem_type, "link")); xml_writer->writeTagsWithData("description", "RSS Aggregator"); for (const auto &harvested_item : harvested_items) { xml_writer->openTag("item"); const auto title(harvested_item.item_.getTitle()); if (not title.empty()) xml_writer->writeTagsWithData("title", harvested_item.item_.getTitle()); xml_writer->writeTagsWithData("link", harvested_item.item_.getLink()); const auto description(HtmlUtil::ShortenText(harvested_item.item_.getDescription(), /*max_length = */ 500)); if (not description.empty()) xml_writer->writeTagsWithData("description", description); xml_writer->writeTagsWithData("pubDate", TimeUtil::TimeTToString(harvested_item.item_.getPubDate(), TimeUtil::RFC822_FORMAT, TimeUtil::UTC)); xml_writer->writeTagsWithData("guid", harvested_item.item_.getId()); xml_writer->closeTag("item", /* suppress_indent */ false); } xml_writer->closeTag("channel"); xml_writer->closeTag("rss"); } struct FeedNameAndURL { std::string name_; std::string url_; public: FeedNameAndURL() = default; FeedNameAndURL(const FeedNameAndURL &other) = default; FeedNameAndURL(const std::string &name, const std::string &url): name_(name), url_(url) { } }; // \return True if a notification email was sent successfully, o/w false. bool SendEmail(const std::string &subsystem_type, const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const std::vector<HarvestedRSSItem> &harvested_items) { const auto template_filename_prefix(UBTools::GetTuelibPath() + "rss_email.template"); std::string template_filename(template_filename_prefix + "." + language); if (not FileUtil::Exists(template_filename)) template_filename = template_filename_prefix + ".en"; static const std::string email_template(FileUtil::ReadStringOrDie(template_filename)); std::string list("<ul>\n"); std::string previous_feed_title; for (const auto &harvested_item : harvested_items) { const bool new_feed(previous_feed_title != harvested_item.feed_title_); if (new_feed) { if (not previous_feed_title.empty()) { // not before the first feed list += "\t</ul>\n"; // end feed item list } list += "\t<li><a href=\"" + harvested_item.website_url_ + "\">" + HtmlUtil::HtmlEscape(harvested_item.feed_title_) + "</a></li>\n"; list += "\t<ul>\n"; // begin feed item list } list += "\t\t<li><a href=\"" + harvested_item.item_.getLink() + "\">" + HtmlUtil::HtmlEscape(harvested_item.item_.getTitle()) + "</a></li>\n"; previous_feed_title = harvested_item.feed_title_; } list += "\t</ul>\n"; // end feed item list list += "</ul>\n"; // end whole list Template::Map names_to_values_map; names_to_values_map.insertScalar("user_name", user_address); names_to_values_map.insertScalar("list", list); names_to_values_map.insertScalar("system", VuFind::CapitalizedUserType(subsystem_type)); names_to_values_map.insertScalar("email_reply_to", subsystem_type + "@ub.uni-tuebingen.de"); const auto email_body(Template::ExpandTemplate(email_template, names_to_values_map)); const auto retcode(EmailSender::SimplerSendEmail(email_sender, { user_email }, GetChannelDescEntry(subsystem_type, "title"), email_body, EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML)); if (retcode <= 299) return true; LOG_WARNING("EmailSender::SimplerSendEmail returned " + std::to_string(retcode) + " while trying to send to \"" + user_email + "\"!"); return false; } const unsigned DEFAULT_XML_INDENT_AMOUNT(2); void GenerateFeed(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items) { XmlWriter xml_writer(FileUtil::OpenOutputFileOrDie("/dev/stdout").release(), XmlWriter::WriteTheXmlDeclaration, DEFAULT_XML_INDENT_AMOUNT); WriteRSSFeedXMLOutput(subsystem_type, harvested_items, &xml_writer); } bool ProcessFeeds(const std::string &user_id, const std::string &rss_feed_last_notification, const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const bool send_email, const std::string &subsystem_type, DbConnection * const db_connection) { db_connection->queryOrDie( "SELECT rss_feeds_id, feed_name, website_url " "FROM tuefind_rss_subscriptions " "LEFT JOIN tuefind_rss_feeds ON tuefind_rss_subscriptions.rss_feeds_id = tuefind_rss_feeds.id " "WHERE tuefind_rss_subscriptions.user_id=" + user_id + " " "ORDER BY feed_name ASC " ); auto feeds_result_set(db_connection->getLastResultSet()); std::vector<HarvestedRSSItem> harvested_items; std::string max_insertion_time; while (const auto feed_row = feeds_result_set.getNextRow()) { const auto feed_id(feed_row["rss_feeds_id"]); const auto feed_name(feed_row["feed_name"]); const auto website_url(feed_row["website_url"]); std::string query( "SELECT item_title,item_description,item_url,item_id,pub_date,insertion_time FROM " "tuefind_rss_items WHERE rss_feeds_id=" + feed_id); if (send_email) query += " AND insertion_time > '" + rss_feed_last_notification + "' "; query += " ORDER BY pub_date ASC"; db_connection->queryOrDie(query); auto items_result_set(db_connection->getLastResultSet()); while (const auto item_row = items_result_set.getNextRow()) { harvested_items.emplace_back(SyndicationFormat::Item(item_row["item_title"], item_row["item_description"], item_row["item_url"], item_row["item_id"], SqlUtil::DatetimeToTimeT(item_row["pub_date"])), feed_name, website_url); const auto insertion_time(item_row["insertion_time"]); if (insertion_time > max_insertion_time) max_insertion_time = insertion_time; } } if (send_email) { if (harvested_items.empty()) return false; if (not SendEmail(subsystem_type, email_sender, user_email, user_address, language, harvested_items)) return true; db_connection->queryOrDie("UPDATE user SET tuefind_rss_feed_last_notification='" + max_insertion_time + "' WHERE id=" + user_id); } else GenerateFeed(subsystem_type, harvested_items); return true; } } // unnamed namespace struct UserInfo { std::string user_id_; std::string first_name_; std::string last_name_; std::string email_; std::string rss_feed_last_notification_; std::string language_code_; public: UserInfo() = default; UserInfo(const UserInfo &other) = default; UserInfo(const std::string &user_id, const std::string &first_name, const std::string &last_name, const std::string &email, const std::string &rss_feed_last_notification, const std::string &language_code) : user_id_(user_id), first_name_(first_name), last_name_(last_name), email_(email), rss_feed_last_notification_(rss_feed_last_notification), language_code_(language_code) { } }; int Main(int argc, char *argv[]) { if (argc != 4) Usage(); std::string sender_email, vufind_user_id; if (std::strcmp(argv[1], "--mode=email") == 0) sender_email = argv[2]; else if (std::strcmp(argv[1], "--mode=rss_xml") == 0) vufind_user_id = argv[2]; else Usage(); const std::string subsystem_type(argv[3]); if (subsystem_type != "ixtheo" and subsystem_type != "relbib" and subsystem_type != "krimdok") LOG_ERROR("subsystem_type must be one of {ixtheo,relbib,krimdok}!"); auto db_connection(DbConnection::VuFindMySQLFactory()); std::string sql_query( "SELECT id,firstname,lastname,email,tuefind_rss_feed_send_emails" ",tuefind_rss_feed_last_notification,last_language FROM user"); if (vufind_user_id.empty()) sql_query += " WHERE tuefind_rss_feed_send_emails IS TRUE"; else sql_query += " WHERE id=" + db_connection.escapeAndQuoteString(vufind_user_id); db_connection.queryOrDie(sql_query); auto user_result_set(db_connection.getLastResultSet()); std::unordered_map<std::string, UserInfo> ids_to_user_infos_map; while (const auto user_row = user_result_set.getNextRow()) { const std::string last_language(user_row["last_language"]); ids_to_user_infos_map[user_row["id"]] = UserInfo(user_row["id"], user_row["firstname"], user_row["lastname"], user_row["email"], user_row["tuefind_rss_feed_last_notification"], (last_language.empty() ? "en" : last_language)); } unsigned feed_generation_count(0), email_sent_count(0); for (const auto &[user_id, user_info] : ids_to_user_infos_map) { if (vufind_user_id.empty() and not EmailSender::IsValidEmailAddress(user_info.email_)) { LOG_WARNING("no valid email address for vufind.user.id " + user_id + "!"); continue; } if (ProcessFeeds(user_id, user_info.rss_feed_last_notification_, sender_email, user_info.email_, MiscUtil::GenerateAddress(user_info.first_name_, user_info.last_name_, "Subscriber"), user_info.language_code_, vufind_user_id.empty(), subsystem_type, &db_connection)) { if (vufind_user_id.empty()) ++email_sent_count; ++feed_generation_count; } } LOG_INFO("Generated " + std::to_string(feed_generation_count) + " RSS feed(s) and sent " + std::to_string(email_sent_count) + " email(s)."); return EXIT_SUCCESS; } <commit_msg>extended query for rss to use subsystem for users, see tuefind/#2118<commit_after>/** \file rss_subset_aggregator.cc * \brief Aggregates RSS feeds. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2021 Universitätsbibliothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <algorithm> #include <map> #include <unordered_map> #include <unordered_set> #include <cinttypes> #include <cstring> #include "Compiler.h" #include "DbConnection.h" #include "DbResultSet.h" #include "EmailSender.h" #include "FileUtil.h" #include "HtmlUtil.h" #include "MiscUtil.h" #include "SqlUtil.h" #include "StringUtil.h" #include "SyndicationFormat.h" #include "Template.h" #include "TimeUtil.h" #include "UBTools.h" #include "VuFind.h" #include "XmlWriter.h" #include "util.h" namespace { [[noreturn]] void Usage() { ::Usage( "--mode=(email|rss_xml) (user_id|sender_email) subsystem_type\n" "If the mode is \"rss_xml\" a VuFind user_id needs to be specified, o/w an error email address should be provided."); } struct HarvestedRSSItem { SyndicationFormat::Item item_; std::string feed_title_; std::string website_url_; HarvestedRSSItem(const SyndicationFormat::Item item, const std::string &feed_title, const std::string &website_url) : item_(item), feed_title_(feed_title), website_url_(website_url) { } }; struct ChannelDesc { std::string title_; std::string link_; public: ChannelDesc(const std::string &title, const std::string &link): title_(title), link_(link) { } }; const std::map<std::string, ChannelDesc> subsystem_type_to_channel_desc_map = { { "relbib", ChannelDesc("RelBib RSS Aggregator", "https://relbib.de/") }, { "ixtheo", ChannelDesc("IxTheo RSS Aggregator", "https://ixtheo.de/") }, { "krimdok", ChannelDesc("KrimDok RSS Aggregator", "https://krimdok.uni-tuebingen.de/") }, }; std::string GetChannelDescEntry(const std::string &subsystem_type, const std::string &entry) { const auto subsystem_type_and_channel_desc(subsystem_type_to_channel_desc_map.find(subsystem_type)); if (subsystem_type_and_channel_desc == subsystem_type_to_channel_desc_map.cend()) LOG_ERROR("unknown subsystem type \"" + subsystem_type + "\"!"); if (entry == "title") return subsystem_type_and_channel_desc->second.title_; if (entry == "link") return subsystem_type_and_channel_desc->second.link_; LOG_ERROR("unknown entry name \"" + entry + "\"!"); } void WriteRSSFeedXMLOutput(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items, XmlWriter * const xml_writer) { xml_writer->openTag("rss", { { "version", "2.0" } }); xml_writer->openTag("channel"); xml_writer->writeTagsWithData("title", GetChannelDescEntry(subsystem_type, "title")); xml_writer->writeTagsWithData("link", GetChannelDescEntry(subsystem_type, "link")); xml_writer->writeTagsWithData("description", "RSS Aggregator"); for (const auto &harvested_item : harvested_items) { xml_writer->openTag("item"); const auto title(harvested_item.item_.getTitle()); if (not title.empty()) xml_writer->writeTagsWithData("title", harvested_item.item_.getTitle()); xml_writer->writeTagsWithData("link", harvested_item.item_.getLink()); const auto description(HtmlUtil::ShortenText(harvested_item.item_.getDescription(), /*max_length = */ 500)); if (not description.empty()) xml_writer->writeTagsWithData("description", description); xml_writer->writeTagsWithData("pubDate", TimeUtil::TimeTToString(harvested_item.item_.getPubDate(), TimeUtil::RFC822_FORMAT, TimeUtil::UTC)); xml_writer->writeTagsWithData("guid", harvested_item.item_.getId()); xml_writer->closeTag("item", /* suppress_indent */ false); } xml_writer->closeTag("channel"); xml_writer->closeTag("rss"); } struct FeedNameAndURL { std::string name_; std::string url_; public: FeedNameAndURL() = default; FeedNameAndURL(const FeedNameAndURL &other) = default; FeedNameAndURL(const std::string &name, const std::string &url): name_(name), url_(url) { } }; // \return True if a notification email was sent successfully, o/w false. bool SendEmail(const std::string &subsystem_type, const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const std::vector<HarvestedRSSItem> &harvested_items) { const auto template_filename_prefix(UBTools::GetTuelibPath() + "rss_email.template"); std::string template_filename(template_filename_prefix + "." + language); if (not FileUtil::Exists(template_filename)) template_filename = template_filename_prefix + ".en"; static const std::string email_template(FileUtil::ReadStringOrDie(template_filename)); std::string list("<ul>\n"); std::string previous_feed_title; for (const auto &harvested_item : harvested_items) { const bool new_feed(previous_feed_title != harvested_item.feed_title_); if (new_feed) { if (not previous_feed_title.empty()) { // not before the first feed list += "\t</ul>\n"; // end feed item list } list += "\t<li><a href=\"" + harvested_item.website_url_ + "\">" + HtmlUtil::HtmlEscape(harvested_item.feed_title_) + "</a></li>\n"; list += "\t<ul>\n"; // begin feed item list } list += "\t\t<li><a href=\"" + harvested_item.item_.getLink() + "\">" + HtmlUtil::HtmlEscape(harvested_item.item_.getTitle()) + "</a></li>\n"; previous_feed_title = harvested_item.feed_title_; } list += "\t</ul>\n"; // end feed item list list += "</ul>\n"; // end whole list Template::Map names_to_values_map; names_to_values_map.insertScalar("user_name", user_address); names_to_values_map.insertScalar("list", list); names_to_values_map.insertScalar("system", VuFind::CapitalizedUserType(subsystem_type)); names_to_values_map.insertScalar("email_reply_to", subsystem_type + "@ub.uni-tuebingen.de"); const auto email_body(Template::ExpandTemplate(email_template, names_to_values_map)); const auto retcode(EmailSender::SimplerSendEmail(email_sender, { user_email }, GetChannelDescEntry(subsystem_type, "title"), email_body, EmailSender::DO_NOT_SET_PRIORITY, EmailSender::HTML)); if (retcode <= 299) return true; LOG_WARNING("EmailSender::SimplerSendEmail returned " + std::to_string(retcode) + " while trying to send to \"" + user_email + "\"!"); return false; } const unsigned DEFAULT_XML_INDENT_AMOUNT(2); void GenerateFeed(const std::string &subsystem_type, const std::vector<HarvestedRSSItem> &harvested_items) { XmlWriter xml_writer(FileUtil::OpenOutputFileOrDie("/dev/stdout").release(), XmlWriter::WriteTheXmlDeclaration, DEFAULT_XML_INDENT_AMOUNT); WriteRSSFeedXMLOutput(subsystem_type, harvested_items, &xml_writer); } bool ProcessFeeds(const std::string &user_id, const std::string &rss_feed_last_notification, const std::string &email_sender, const std::string &user_email, const std::string &user_address, const std::string &language, const bool send_email, const std::string &subsystem_type, DbConnection * const db_connection) { db_connection->queryOrDie( "SELECT rss_feeds_id, feed_name, website_url " "FROM tuefind_rss_subscriptions " "LEFT JOIN tuefind_rss_feeds ON tuefind_rss_subscriptions.rss_feeds_id = tuefind_rss_feeds.id " "WHERE tuefind_rss_subscriptions.user_id=" + user_id + " " "ORDER BY feed_name ASC " ); auto feeds_result_set(db_connection->getLastResultSet()); std::vector<HarvestedRSSItem> harvested_items; std::string max_insertion_time; while (const auto feed_row = feeds_result_set.getNextRow()) { const auto feed_id(feed_row["rss_feeds_id"]); const auto feed_name(feed_row["feed_name"]); const auto website_url(feed_row["website_url"]); std::string query( "SELECT item_title,item_description,item_url,item_id,pub_date,insertion_time FROM " "tuefind_rss_items WHERE rss_feeds_id=" + feed_id); if (send_email) query += " AND insertion_time > '" + rss_feed_last_notification + "' "; query += " ORDER BY pub_date ASC"; db_connection->queryOrDie(query); auto items_result_set(db_connection->getLastResultSet()); while (const auto item_row = items_result_set.getNextRow()) { harvested_items.emplace_back(SyndicationFormat::Item(item_row["item_title"], item_row["item_description"], item_row["item_url"], item_row["item_id"], SqlUtil::DatetimeToTimeT(item_row["pub_date"])), feed_name, website_url); const auto insertion_time(item_row["insertion_time"]); if (insertion_time > max_insertion_time) max_insertion_time = insertion_time; } } if (send_email) { if (harvested_items.empty()) return false; if (not SendEmail(subsystem_type, email_sender, user_email, user_address, language, harvested_items)) return true; db_connection->queryOrDie("UPDATE user SET tuefind_rss_feed_last_notification='" + max_insertion_time + "' WHERE id=" + user_id); } else GenerateFeed(subsystem_type, harvested_items); return true; } } // unnamed namespace struct UserInfo { std::string user_id_; std::string first_name_; std::string last_name_; std::string email_; std::string rss_feed_last_notification_; std::string language_code_; public: UserInfo() = default; UserInfo(const UserInfo &other) = default; UserInfo(const std::string &user_id, const std::string &first_name, const std::string &last_name, const std::string &email, const std::string &rss_feed_last_notification, const std::string &language_code) : user_id_(user_id), first_name_(first_name), last_name_(last_name), email_(email), rss_feed_last_notification_(rss_feed_last_notification), language_code_(language_code) { } }; int Main(int argc, char *argv[]) { if (argc != 4) Usage(); std::string sender_email, vufind_user_id; if (std::strcmp(argv[1], "--mode=email") == 0) sender_email = argv[2]; else if (std::strcmp(argv[1], "--mode=rss_xml") == 0) vufind_user_id = argv[2]; else Usage(); const std::string subsystem_type(argv[3]); if (subsystem_type != "ixtheo" and subsystem_type != "relbib" and subsystem_type != "krimdok") LOG_ERROR("subsystem_type must be one of {ixtheo,relbib,krimdok}!"); auto db_connection(DbConnection::VuFindMySQLFactory()); std::string sql_query( "SELECT id,firstname,lastname,email,tuefind_rss_feed_send_emails" ",tuefind_rss_feed_last_notification,last_language FROM user"); if (vufind_user_id.empty()) sql_query += " WHERE tuefind_rss_feed_send_emails IS TRUE"; else sql_query += " WHERE id=" + db_connection.escapeAndQuoteString(vufind_user_id); sql_query += " AND ixtheo_user_type='" + subsystem_type + "'"; db_connection.queryOrDie(sql_query); auto user_result_set(db_connection.getLastResultSet()); std::unordered_map<std::string, UserInfo> ids_to_user_infos_map; while (const auto user_row = user_result_set.getNextRow()) { const std::string last_language(user_row["last_language"]); ids_to_user_infos_map[user_row["id"]] = UserInfo(user_row["id"], user_row["firstname"], user_row["lastname"], user_row["email"], user_row["tuefind_rss_feed_last_notification"], (last_language.empty() ? "en" : last_language)); } unsigned feed_generation_count(0), email_sent_count(0); for (const auto &[user_id, user_info] : ids_to_user_infos_map) { if (vufind_user_id.empty() and not EmailSender::IsValidEmailAddress(user_info.email_)) { LOG_WARNING("no valid email address for vufind.user.id " + user_id + "!"); continue; } if (ProcessFeeds(user_id, user_info.rss_feed_last_notification_, sender_email, user_info.email_, MiscUtil::GenerateAddress(user_info.first_name_, user_info.last_name_, "Subscriber"), user_info.language_code_, vufind_user_id.empty(), subsystem_type, &db_connection)) { if (vufind_user_id.empty()) ++email_sent_count; ++feed_generation_count; } } LOG_INFO("Generated " + std::to_string(feed_generation_count) + " RSS feed(s) and sent " + std::to_string(email_sent_count) + " email(s)."); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/////////////////////////////////////////////////////////////////////////////// // droppable_accumulator.hpp // // Copyright 2005 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_DROPPABLE_ACCUMULATOR_HPP_EAN_13_12_2005 #define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_DROPPABLE_ACCUMULATOR_HPP_EAN_13_12_2005 #include <new> #include <boost/assert.hpp> #include <boost/mpl/apply.hpp> #include <boost/aligned_storage.hpp> #include <boost/accumulators/framework/depends_on.hpp> // for feature_of #include <boost/accumulators/framework/parameters/accumulator.hpp> // for accumulator namespace pdalboost{} namespace boost = pdalboost; namespace pdalboost{ namespace accumulators { template<typename Accumulator> struct droppable_accumulator; namespace detail { /////////////////////////////////////////////////////////////////////////////// // add_ref_visitor // a fusion function object for add_ref'ing accumulators template<typename Args> struct add_ref_visitor { explicit add_ref_visitor(Args const &args) : args_(args) { } template<typename Accumulator> void operator ()(Accumulator &acc) const { typedef typename Accumulator::feature_tag::dependencies dependencies; acc.add_ref(this->args_); // Also add_ref accumulators that this feature depends on this->args_[accumulator].template visit_if<detail::contains_feature_of_<dependencies> >( *this ); } private: add_ref_visitor &operator =(add_ref_visitor const &); Args const &args_; }; template<typename Args> add_ref_visitor<Args> make_add_ref_visitor(Args const &args) { return add_ref_visitor<Args>(args); } /////////////////////////////////////////////////////////////////////////////// // drop_visitor // a fusion function object for dropping accumulators template<typename Args> struct drop_visitor { explicit drop_visitor(Args const &args) : args_(args) { } template<typename Accumulator> void operator ()(Accumulator &acc) const { if(typename Accumulator::is_droppable()) { typedef typename Accumulator::feature_tag::dependencies dependencies; acc.drop(this->args_); // Also drop accumulators that this feature depends on this->args_[accumulator].template visit_if<detail::contains_feature_of_<dependencies> >( *this ); } } private: drop_visitor &operator =(drop_visitor const &); Args const &args_; }; template<typename Args> drop_visitor<Args> make_drop_visitor(Args const &args) { return drop_visitor<Args>(args); } } ////////////////////////////////////////////////////////////////////////// // droppable_accumulator_base template<typename Accumulator> struct droppable_accumulator_base : Accumulator { typedef droppable_accumulator_base base; typedef mpl::true_ is_droppable; typedef typename Accumulator::result_type result_type; template<typename Args> droppable_accumulator_base(Args const &args) : Accumulator(args) , ref_count_(0) { } template<typename Args> void operator ()(Args const &args) { if(!this->is_dropped()) { this->Accumulator::operator ()(args); } } template<typename Args> void add_ref(Args const &) { ++this->ref_count_; } template<typename Args> void drop(Args const &args) { BOOST_ASSERT(0 < this->ref_count_); if(1 == this->ref_count_) { static_cast<droppable_accumulator<Accumulator> *>(this)->on_drop(args); } --this->ref_count_; } bool is_dropped() const { return 0 == this->ref_count_; } private: int ref_count_; }; ////////////////////////////////////////////////////////////////////////// // droppable_accumulator // this can be specialized for any type that needs special handling template<typename Accumulator> struct droppable_accumulator : droppable_accumulator_base<Accumulator> { template<typename Args> droppable_accumulator(Args const &args) : droppable_accumulator::base(args) { } }; ////////////////////////////////////////////////////////////////////////// // with_cached_result template<typename Accumulator> struct with_cached_result : Accumulator { typedef typename Accumulator::result_type result_type; template<typename Args> with_cached_result(Args const &args) : Accumulator(args) , cache() { } with_cached_result(with_cached_result const &that) : Accumulator(*static_cast<Accumulator const *>(&that)) , cache() { if(that.has_result()) { this->set(that.get()); } } ~with_cached_result() { // Since this is a base class of droppable_accumulator_base, // this destructor is called before any of droppable_accumulator_base's // members get cleaned up, including is_dropped, so the following // call to has_result() is valid. if(this->has_result()) { this->get().~result_type(); } } template<typename Args> void on_drop(Args const &args) { // cache the result at the point this calcuation was dropped BOOST_ASSERT(!this->has_result()); this->set(this->Accumulator::result(args)); } template<typename Args> result_type result(Args const &args) const { return this->has_result() ? this->get() : this->Accumulator::result(args); } private: with_cached_result &operator =(with_cached_result const &); void set(result_type const &r) { ::new(this->cache.address()) result_type(r); } result_type const &get() const { return *static_cast<result_type const *>(this->cache.address()); } bool has_result() const { typedef with_cached_result<Accumulator> this_type; typedef droppable_accumulator_base<this_type> derived_type; return static_cast<derived_type const *>(this)->is_dropped(); } aligned_storage<sizeof(result_type)> cache; }; namespace tag { template<typename Feature> struct as_droppable { typedef droppable<Feature> type; }; template<typename Feature> struct as_droppable<droppable<Feature> > { typedef droppable<Feature> type; }; ////////////////////////////////////////////////////////////////////////// // droppable template<typename Feature> struct droppable : as_feature<Feature>::type { typedef typename as_feature<Feature>::type feature_type; typedef typename feature_type::dependencies tmp_dependencies_; typedef typename mpl::transform< typename feature_type::dependencies , as_droppable<mpl::_1> >::type dependencies; struct impl { template<typename Sample, typename Weight> struct apply { typedef droppable_accumulator< typename mpl::apply2<typename feature_type::impl, Sample, Weight>::type > type; }; }; }; } // make droppable<tag::feature(modifier)> work template<typename Feature> struct as_feature<tag::droppable<Feature> > { typedef tag::droppable<typename as_feature<Feature>::type> type; }; // make droppable<tag::mean> work with non-void weights (should become // droppable<tag::weighted_mean> template<typename Feature> struct as_weighted_feature<tag::droppable<Feature> > { typedef tag::droppable<typename as_weighted_feature<Feature>::type> type; }; // for the purposes of feature-based dependency resolution, // droppable<Foo> provides the same feature as Foo template<typename Feature> struct feature_of<tag::droppable<Feature> > : feature_of<Feature> { }; // Note: Usually, the extractor is pulled into the accumulators namespace with // a using directive, not the tag. But the droppable<> feature doesn't have an // extractor, so we can put the droppable tag in the accumulators namespace // without fear of a name conflict. using tag::droppable; }} // namespace pdalboost::accumulators #endif <commit_msg>patch for boost bug #6535 to allow compilation of boost::accumulators::droppable on msvc<commit_after>/////////////////////////////////////////////////////////////////////////////// // droppable_accumulator.hpp // // Copyright 2005 Eric Niebler. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_DROPPABLE_ACCUMULATOR_HPP_EAN_13_12_2005 #define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_DROPPABLE_ACCUMULATOR_HPP_EAN_13_12_2005 #include <new> #include <boost/assert.hpp> #include <boost/mpl/apply.hpp> #include <boost/aligned_storage.hpp> #include <boost/accumulators/framework/depends_on.hpp> // for feature_of #include <boost/accumulators/framework/parameters/accumulator.hpp> // for accumulator namespace pdalboost{} namespace boost = pdalboost; namespace pdalboost{ namespace accumulators { template<typename Accumulator> struct droppable_accumulator; namespace detail { /////////////////////////////////////////////////////////////////////////////// // add_ref_visitor // a fusion function object for add_ref'ing accumulators template<typename Args> struct add_ref_visitor { explicit add_ref_visitor(Args const &args) : args_(args) { } template<typename Accumulator> void operator ()(Accumulator &acc) const { typedef typename Accumulator::feature_tag::dependencies dependencies; acc.add_ref(this->args_); // Also add_ref accumulators that this feature depends on this->args_[accumulator].template visit_if<detail::contains_feature_of_<dependencies> >( *this ); } private: add_ref_visitor &operator =(add_ref_visitor const &); Args const &args_; }; template<typename Args> add_ref_visitor<Args> make_add_ref_visitor(Args const &args) { return add_ref_visitor<Args>(args); } /////////////////////////////////////////////////////////////////////////////// // drop_visitor // a fusion function object for dropping accumulators template<typename Args> struct drop_visitor { explicit drop_visitor(Args const &args) : args_(args) { } template<typename Accumulator> void operator ()(Accumulator &acc) const { if(typename Accumulator::is_droppable()) { typedef typename Accumulator::feature_tag::dependencies dependencies; acc.drop(this->args_); // Also drop accumulators that this feature depends on this->args_[accumulator].template visit_if<detail::contains_feature_of_<dependencies> >( *this ); } } private: drop_visitor &operator =(drop_visitor const &); Args const &args_; }; template<typename Args> drop_visitor<Args> make_drop_visitor(Args const &args) { return drop_visitor<Args>(args); } } ////////////////////////////////////////////////////////////////////////// // droppable_accumulator_base template<typename Accumulator> struct droppable_accumulator_base : Accumulator { typedef droppable_accumulator_base base; typedef mpl::true_ is_droppable; typedef typename Accumulator::result_type result_type; template<typename Args> droppable_accumulator_base(Args const &args) : Accumulator(args) , ref_count_(0) { } droppable_accumulator_base(droppable_accumulator_base const &that) : Accumulator(*static_cast<Accumulator const *>(&that)) , ref_count_(that.ref_count_) { } template<typename Args> void operator ()(Args const &args) { if(!this->is_dropped()) { this->Accumulator::operator ()(args); } } template<typename Args> void add_ref(Args const &) { ++this->ref_count_; } template<typename Args> void drop(Args const &args) { BOOST_ASSERT(0 < this->ref_count_); if(1 == this->ref_count_) { static_cast<droppable_accumulator<Accumulator> *>(this)->on_drop(args); } --this->ref_count_; } bool is_dropped() const { return 0 == this->ref_count_; } private: int ref_count_; }; ////////////////////////////////////////////////////////////////////////// // droppable_accumulator // this can be specialized for any type that needs special handling template<typename Accumulator> struct droppable_accumulator : droppable_accumulator_base<Accumulator> { template<typename Args> droppable_accumulator(Args const &args) : droppable_accumulator::base(args) { } droppable_accumulator(droppable_accumulator const &that) : droppable_accumulator::base(*static_cast<droppable_accumulator::base const *>(&that)) { } }; ////////////////////////////////////////////////////////////////////////// // with_cached_result template<typename Accumulator> struct with_cached_result : Accumulator { typedef typename Accumulator::result_type result_type; template<typename Args> with_cached_result(Args const &args) : Accumulator(args) , cache() { } with_cached_result(with_cached_result const &that) : Accumulator(*static_cast<Accumulator const *>(&that)) , cache() { if(that.has_result()) { this->set(that.get()); } } ~with_cached_result() { // Since this is a base class of droppable_accumulator_base, // this destructor is called before any of droppable_accumulator_base's // members get cleaned up, including is_dropped, so the following // call to has_result() is valid. if(this->has_result()) { this->get().~result_type(); } } template<typename Args> void on_drop(Args const &args) { // cache the result at the point this calcuation was dropped BOOST_ASSERT(!this->has_result()); this->set(this->Accumulator::result(args)); } template<typename Args> result_type result(Args const &args) const { return this->has_result() ? this->get() : this->Accumulator::result(args); } private: with_cached_result &operator =(with_cached_result const &); void set(result_type const &r) { ::new(this->cache.address()) result_type(r); } result_type const &get() const { return *static_cast<result_type const *>(this->cache.address()); } bool has_result() const { typedef with_cached_result<Accumulator> this_type; typedef droppable_accumulator_base<this_type> derived_type; return static_cast<derived_type const *>(this)->is_dropped(); } aligned_storage<sizeof(result_type)> cache; }; namespace tag { template<typename Feature> struct as_droppable { typedef droppable<Feature> type; }; template<typename Feature> struct as_droppable<droppable<Feature> > { typedef droppable<Feature> type; }; ////////////////////////////////////////////////////////////////////////// // droppable template<typename Feature> struct droppable : as_feature<Feature>::type { typedef typename as_feature<Feature>::type feature_type; typedef typename feature_type::dependencies tmp_dependencies_; typedef typename mpl::transform< typename feature_type::dependencies , as_droppable<mpl::_1> >::type dependencies; struct impl { template<typename Sample, typename Weight> struct apply { typedef droppable_accumulator< typename mpl::apply2<typename feature_type::impl, Sample, Weight>::type > type; }; }; }; } // make droppable<tag::feature(modifier)> work template<typename Feature> struct as_feature<tag::droppable<Feature> > { typedef tag::droppable<typename as_feature<Feature>::type> type; }; // make droppable<tag::mean> work with non-void weights (should become // droppable<tag::weighted_mean> template<typename Feature> struct as_weighted_feature<tag::droppable<Feature> > { typedef tag::droppable<typename as_weighted_feature<Feature>::type> type; }; // for the purposes of feature-based dependency resolution, // droppable<Foo> provides the same feature as Foo template<typename Feature> struct feature_of<tag::droppable<Feature> > : feature_of<Feature> { }; // Note: Usually, the extractor is pulled into the accumulators namespace with // a using directive, not the tag. But the droppable<> feature doesn't have an // extractor, so we can put the droppable tag in the accumulators namespace // without fear of a name conflict. using tag::droppable; }} // namespace pdalboost::accumulators #endif <|endoftext|>
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h" #include <fstream> #include <memory> #include "absl/flags/flag.h" #include "absl/status/status.h" #include "absl/strings/cord.h" #include "tensorflow/lite/core/shims/cc/shims_test_util.h" #include "tensorflow/lite/kernels/builtin_op_kernels.h" #include "tensorflow/lite/mutable_op_resolver.h" #include "tensorflow_lite_support/cc/port/gmock.h" #include "tensorflow_lite_support/cc/port/gtest.h" #include "tensorflow_lite_support/cc/port/status_matchers.h" #include "tensorflow_lite_support/cc/task/core/task_api_factory.h" #include "tensorflow_lite_support/cc/task/core/task_utils.h" #include "tensorflow_lite_support/cc/task/core/tflite_engine.h" #include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h" #include "tensorflow_lite_support/cc/test/test_utils.h" #include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h" namespace tflite { namespace task { namespace processor { namespace { using ::testing::ElementsAreArray; using ::testing::HasSubstr; using ::testing::Optional; using ::tflite::support::kTfLiteSupportPayload; using ::tflite::support::StatusOr; using ::tflite::support::TfLiteSupportStatus; using ::tflite::task::JoinPath; using ::tflite::task::core::PopulateTensor; using ::tflite::task::core::TaskAPIFactory; using ::tflite::task::core::TfLiteEngine; using ::tflite::task::vision::DecodeImageFromFile; using ::tflite::task::vision::FrameBuffer; using ::tflite::task::vision::ImageData; constexpr char kTestDataDirectory[] = "tensorflow_lite_support/cc/test/testdata/task/vision/"; constexpr char kDilatedConvolutionModelWithMetaData[] = "dilated_conv.tflite"; StatusOr<ImageData> LoadImage(std::string image_name) { return DecodeImageFromFile( JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name)); } class DynamicInputTest : public tflite_shims::testing::Test { public: void SetUp() { engine_ = absl::make_unique<TfLiteEngine>(); engine_->BuildModelFromFile(JoinPath("./", kTestDataDirectory, kDilatedConvolutionModelWithMetaData)); engine_->InitInterpreter(); SUPPORT_ASSERT_OK_AND_ASSIGN(preprocessor_, ImagePreprocessor::Create(engine_.get(), {0})); } protected: std::unique_ptr<ImagePreprocessor> preprocessor_ = nullptr; std::unique_ptr<TfLiteEngine> engine_ = nullptr; }; // See if input tensor dims signature for height and width is -1 // because it is so in the model. TEST_F(DynamicInputTest, InputHeightAndWidthMutable) { const TfLiteIntArray *input_dims_signature = engine_->GetInputs()[0]->dims_signature; EXPECT_EQ(input_dims_signature->data[1], -1); EXPECT_EQ(input_dims_signature->data[2], -1); } // See if output tensor has been re-dimmed as per the input // tensor. Expected shape: (1, input_height, input_width, 16). TEST_F(DynamicInputTest, OutputDimensionCheck) { SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg")); std::unique_ptr<FrameBuffer> image_frame_buffer = CreateFromRgbRawBuffer( image.pixel_data, FrameBuffer::Dimension{image.width, image.height}); preprocessor_->Preprocess(*image_frame_buffer); absl::Status status = engine_->interpreter_wrapper()->InvokeWithoutFallback(); EXPECT_TRUE(status.ok()); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[0], 1); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[1], engine_->GetInputs()[0]->dims->data[1]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[2], engine_->GetInputs()[0]->dims->data[2]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[3], 16); } // Compare pre-processed input with an already pre-processed // golden image. TEST_F(DynamicInputTest, GoldenImageComparison) { SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg")); std::unique_ptr<FrameBuffer> image_frame_buffer = CreateFromRgbRawBuffer( image.pixel_data, FrameBuffer::Dimension{image.width, image.height}); preprocessor_->Preprocess(*image_frame_buffer); // Check the processed input image. float *processed_input_data = tflite::task::core::AssertAndReturnTypedTensor<float>( engine_->GetInputs()[0]); bool is_equal = true; float epsilon = 0.1f; std::string file_path = JoinPath("./", kTestDataDirectory, "burger_normalized.bin"); std::ifstream golden_image(file_path, std::ios::binary); // Input read success check. is_equal &= golden_image.peek() != std::ifstream::traits_type::eof(); std::vector<uint8_t> buffer(std::istreambuf_iterator<char>(golden_image), {}); float *val_ptr = reinterpret_cast<float *>(buffer.data()); for (size_t i = 0; i < buffer.size() / sizeof(float); ++i) { is_equal &= std::fabs(*val_ptr - *processed_input_data) <= epsilon; ++val_ptr; ++processed_input_data; } EXPECT_TRUE(is_equal); } } // namespace } // namespace processor } // namespace task } // namespace tflite <commit_msg>Move image processing to SetUp + Remove first test<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h" #include <fstream> #include <memory> #include "absl/flags/flag.h" #include "absl/status/status.h" #include "absl/strings/cord.h" #include "tensorflow/lite/core/shims/cc/shims_test_util.h" #include "tensorflow/lite/kernels/builtin_op_kernels.h" #include "tensorflow/lite/mutable_op_resolver.h" #include "tensorflow_lite_support/cc/port/gmock.h" #include "tensorflow_lite_support/cc/port/gtest.h" #include "tensorflow_lite_support/cc/port/status_matchers.h" #include "tensorflow_lite_support/cc/task/core/task_api_factory.h" #include "tensorflow_lite_support/cc/task/core/task_utils.h" #include "tensorflow_lite_support/cc/task/core/tflite_engine.h" #include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h" #include "tensorflow_lite_support/cc/test/test_utils.h" #include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h" namespace tflite { namespace task { namespace processor { namespace { using ::tflite::support::kTfLiteSupportPayload; using ::tflite::support::StatusOr; using ::tflite::support::TfLiteSupportStatus; using ::tflite::task::JoinPath; using ::tflite::task::core::TfLiteEngine; using ::tflite::task::vision::DecodeImageFromFile; using ::tflite::task::vision::FrameBuffer; using ::tflite::task::vision::ImageData; constexpr char kTestDataDirectory[] = "tensorflow_lite_support/cc/test/testdata/task/vision/"; constexpr char kDilatedConvolutionModelWithMetaData[] = "dilated_conv.tflite"; StatusOr<ImageData> LoadImage(std::string image_name) { return DecodeImageFromFile( JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name)); } class DynamicInputTest : public tflite_shims::testing::Test { public: void SetUp() { engine_ = absl::make_unique<TfLiteEngine>(); engine_->BuildModelFromFile(JoinPath("./", kTestDataDirectory, kDilatedConvolutionModelWithMetaData)); engine_->InitInterpreter(); SUPPORT_ASSERT_OK_AND_ASSIGN(auto preprocessor, ImagePreprocessor::Create(engine_.get(), {0})); SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg")); std::unique_ptr<FrameBuffer> image_frame_buffer = CreateFromRgbRawBuffer( image.pixel_data, FrameBuffer::Dimension{image.width, image.height}); preprocessor->Preprocess(*image_frame_buffer); } protected: std::unique_ptr<TfLiteEngine> engine_ = nullptr; }; // See if output tensor has been re-dimmed as per the input // tensor. Expected shape: (1, input_height, input_width, 16). TEST_F(DynamicInputTest, OutputDimensionCheck) { absl::Status status = engine_->interpreter_wrapper()->InvokeWithoutFallback(); EXPECT_TRUE(status.ok()); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[0], 1); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[1], engine_->GetInputs()[0]->dims->data[1]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[2], engine_->GetInputs()[0]->dims->data[2]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[3], 16); } // Compare pre-processed input with an already pre-processed // golden image. TEST_F(DynamicInputTest, GoldenImageComparison) { // Check the processed input image. float *processed_input_data = tflite::task::core::AssertAndReturnTypedTensor<float>( engine_->GetInputs()[0]); bool is_equal = true; float epsilon = 0.1f; std::string file_path = JoinPath("./", kTestDataDirectory, "burger_normalized.bin"); std::ifstream golden_image(file_path, std::ios::binary); // Input read success check. is_equal &= golden_image.peek() != std::ifstream::traits_type::eof(); std::vector<uint8_t> buffer(std::istreambuf_iterator<char>(golden_image), {}); float *val_ptr = reinterpret_cast<float *>(buffer.data()); for (size_t i = 0; i < buffer.size() / sizeof(float); ++i) { is_equal &= std::fabs(*val_ptr - *processed_input_data) <= epsilon; ++val_ptr; ++processed_input_data; } EXPECT_TRUE(is_equal); } } // namespace } // namespace processor } // namespace task } // namespace tflite <|endoftext|>
<commit_before>e8e39e78-ad58-11e7-9597-ac87a332f658<commit_msg>testing<commit_after>e9541778-ad58-11e7-a9eb-ac87a332f658<|endoftext|>
<commit_before>// Copyright 2017 Rick van Schijndel #include <Arduino.h> #include <stdio.h> #include <Bounce2.h> #include <U8g2lib.h> // assets #include "logo.xbm" #include "player.xbm" #include "obstacle.xbm" #include "asset.h" #include "player.h" #include "game.h" #include "screen_info.h" #ifdef U8X8_HAVE_HW_SPI #include <SPI.h> #endif #ifdef U8X8_HAVE_HW_I2C #include <Wire.h> #endif const uint8_t kButtonPin = D3; // Assets Asset bootup_screen(bootup_width, bootup_height, bootup_bits); Asset player_asset(player_width, player_height, player_bits); Asset logo_asset(bootup_width, bootup_height, bootup_bits); Asset obstacle_asset(obstacle_width, obstacle_height, obstacle_bits); // The display object U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0); Bounce button; Obstacle obstacles[] = {Obstacle(obstacle_asset)}; const size_t obstacles_size = sizeof(obstacles) / sizeof(obstacles[0]); Game game(bootup_screen, player_asset, obstacles, obstacles_size, &u8g2); void setupButton() { pinMode(kButtonPin, INPUT_PULLUP); button.attach(kButtonPin); button.interval(10); } void setupGraphics() { u8g2.begin(); u8g2.setFlipMode(0); u8g2.setFont(u8g2_font_artossans8_8r); } void setup(void) { setupGraphics(); setupButton(); Serial.begin(115200); delay(1000); } bool buttonPressed = false; void loop(void) { if (button.update()) { buttonPressed = button.read(); } else { buttonPressed = false; } game.Update(buttonPressed); game.Draw(); } <commit_msg>Fix naming for bootup asset<commit_after>// Copyright 2017 Rick van Schijndel #include <Arduino.h> #include <stdio.h> #include <Bounce2.h> #include <U8g2lib.h> // assets #include "logo.xbm" #include "player.xbm" #include "obstacle.xbm" #include "asset.h" #include "player.h" #include "game.h" #include "screen_info.h" #ifdef U8X8_HAVE_HW_SPI #include <SPI.h> #endif #ifdef U8X8_HAVE_HW_I2C #include <Wire.h> #endif const uint8_t kButtonPin = D3; // Assets Asset bootup_screen(logo_width, logo_height, logo_bits); Asset player_asset(player_width, player_height, player_bits); Asset obstacle_asset(obstacle_width, obstacle_height, obstacle_bits); // The display object U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0); Bounce button; Obstacle obstacles[] = {Obstacle(obstacle_asset)}; const size_t obstacles_size = sizeof(obstacles) / sizeof(obstacles[0]); Game game(bootup_screen, player_asset, obstacles, obstacles_size, &u8g2); void setupButton() { pinMode(kButtonPin, INPUT_PULLUP); button.attach(kButtonPin); button.interval(10); } void setupGraphics() { u8g2.begin(); u8g2.setFlipMode(0); u8g2.setFont(u8g2_font_artossans8_8r); } void setup(void) { setupGraphics(); setupButton(); Serial.begin(115200); delay(1000); } bool buttonPressed = false; void loop(void) { if (button.update()) { buttonPressed = button.read(); } else { buttonPressed = false; } game.Update(buttonPressed); game.Draw(); } <|endoftext|>
<commit_before>#include "window.h" #include <cmath> // for sine stuff Window::Window() : plot( QString("Spectrum Analyer") ), gain(5), count(0) // <-- 'c++ initialisation list' - google it! { // set up the gain knob // knob.setValue(gain); help_text.setReadOnly(1); help_text.setText(infoStr); playBtn.setText("Play"); stopBtn.setText("Stop"); quitBtn.setText("Quit"); bin_arr_pos = 4; spinner.setValue(bin_arr[bin_arr_pos]); spinner.setRange(8,1024); spinner.setSuffix(" bins"); connect(&spinner, SIGNAL(valueChanged(int)), SLOT(setBins(int)) ); // use the Qt signals/slots framework to update the gain - // every time the knob is moved, the setGain function will be called connect( &knob, SIGNAL(valueChanged(double)), SLOT(setGain(double)) ); // set up the thermometer thermo.setFillBrush( QBrush(Qt::green) ); thermo.setRange(0, 10); thermo.show(); // set up the initial plot data for( int index=0; index<plotDataSize; ++index ) { xData[index] = index; yData[index] = gain * sin( M_PI * index/15 ); } for( int iindex=0; iindex<(sampRate/2); ++iindex ) { fft_x[iindex]=iindex; fft_y[iindex]=iindex; } // make a plot curve from the data and attach it to the plot amp_curve.setSamples(xData, yData, plotDataSize); amp_curve.attach(&plot); // don't need to fill up pre samples, can all be 0 spec_curve.setSamples(fft_x, fft_y, sampRate/2); spec_curve.attach(&spec_plot); plot.replot(); spec_plot.replot(); plot.setAxisTitle(plot.xBottom,time_x); plot.setAxisTitle(plot.yLeft, time_y); spec_plot.setAxisTitle(spec_plot.xBottom,spec_x); spec_plot.setAxisTitle(spec_plot.yLeft,spec_y); plot.show(); spec_plot.show(); hTimeL.addWidget(&thermo); hTimeL.addWidget(&plot); hSpecL.addLayout(&vSpecOptionsL); hSpecL.addWidget(&spec_plot); vSpecOptionsL.addWidget(&spinner); vSpecOptionsL.addWidget(&help_text); vSpecOptionsL.addLayout(&vControlsL); hPlayPauseL.addWidget(&playBtn); hPlayPauseL.addWidget(&stopBtn); vControlsL.addLayout(&hPlayPauseL); vControlsL.addWidget(&quitBtn); vMainL.addLayout(&hTimeL); vMainL.addLayout(&hSpecL); setLayout(&vMainL); } void Window::timerEvent( QTimerEvent * ) { // generate an sine wave input for example purposes - you must get yours from the A/D! double inVal = gain * sin( M_PI * count/15.0 ); ++count; // add the new input to the plot memmove( yData, yData+1, (plotDataSize-1) * sizeof(double) ); yData[plotDataSize-1] = inVal; amp_curve.setSamples(xData, yData, plotDataSize); plot.replot(); // set the thermometer value thermo.setValue( inVal +5); if(thermo.value()>0){ thermo.setFillBrush ( QBrush(Qt::green)); } if(thermo.value()>7){ thermo.setFillBrush ( QBrush(Qt::yellow)); } if(thermo.value()>9){ thermo.setFillBrush ( QBrush(Qt::red)); } // could be method, could be threaded if(count > fft.fft_in_size){ for(int i=0; i<fft.fft_in_size;i++){ fft.fft_in[i]= yData[i]; } fft.setPlan(); fft.executeFFT(); for(int k=0; k<fft.fft_out_size; k++){ fft_y[k]=fft.fft_out[k][0]; } spec_curve.setSamples(fft_x,fft_y,sampRate/2); spec_plot.replot(); } } // this function can be used to change the gain of the A/D internal amplifier void Window::setGain(double gain) { // for example purposes just change the amplitude of the generated input this->gain = gain; } void Window::setBins(int bins) { if(bins>pbins){ pbins = bin_arr[bin_arr_pos++]; } else { pbins = bin_arr[bin_arr_pos--]; } this->bins = pbins; } <commit_msg>Adding control button methods<commit_after>#include "window.h" #include <cmath> // for sine stuff Window::Window() : plot( QString("Spectrum Analyer") ), gain(5), count(0) // <-- 'c++ initialisation list' - google it! { // set up the gain knob // knob.setValue(gain); help_text.setReadOnly(1); help_text.setText(infoStr); playBtn.setText("Play"); stopBtn.setText("Stop"); quitBtn.setText("Quit"); // either valueChanged or onClick? connect ( &play, SIGNAL(valueChanged(double)), SLOT(play()) ); connect ( &stop, SIGNAL(valueChanged(double)), SLOT(stop()) ); connect ( &quit, SIGNAL(valueChanged(double)), SLOT(quit()) ); bin_arr_pos = 4; spinner.setValue(bin_arr[bin_arr_pos]); spinner.setRange(8,1024); spinner.setSuffix(" bins"); connect(&spinner, SIGNAL(valueChanged(int)), SLOT(setBins(int)) ); // use the Qt signals/slots framework to update the gain - // every time the knob is moved, the setGain function will be called connect( &knob, SIGNAL(valueChanged(double)), SLOT(setGain(double)) ); // set up the thermometer thermo.setFillBrush( QBrush(Qt::green) ); thermo.setRange(0, 10); thermo.show(); // set up the initial plot data for( int index=0; index<plotDataSize; ++index ) { xData[index] = index; yData[index] = gain * sin( M_PI * index/15 ); } for( int iindex=0; iindex<(sampRate/2); ++iindex ) { fft_x[iindex]=iindex; fft_y[iindex]=0; } // make a plot curve from the data and attach it to the plot amp_curve.setSamples(xData, yData, plotDataSize); amp_curve.attach(&plot); // don't need to fill up pre samples, can all be 0 spec_curve.setSamples(fft_x, fft_y, sampRate/2); spec_curve.attach(&spec_plot); plot.replot(); spec_plot.replot(); plot.setAxisTitle(plot.xBottom,time_x); plot.setAxisTitle(plot.yLeft, time_y); spec_plot.setAxisTitle(spec_plot.xBottom,spec_x); spec_plot.setAxisTitle(spec_plot.yLeft,spec_y); plot.show(); spec_plot.show(); hTimeL.addWidget(&thermo); hTimeL.addWidget(&plot); hSpecL.addLayout(&vSpecOptionsL); hSpecL.addWidget(&spec_plot); vSpecOptionsL.addWidget(&spinner); vSpecOptionsL.addWidget(&help_text); vSpecOptionsL.addLayout(&vControlsL); hPlayPauseL.addWidget(&playBtn); hPlayPauseL.addWidget(&stopBtn); vControlsL.addLayout(&hPlayPauseL); vControlsL.addWidget(&quitBtn); vMainL.addLayout(&hTimeL); vMainL.addLayout(&hSpecL); setLayout(&vMainL); } void Window::timerEvent( QTimerEvent * ) { // generate an sine wave input for example purposes - you must get yours from the A/D! double inVal = gain * sin( M_PI * count/15.0 ); ++count; // add the new input to the plot memmove( yData, yData+1, (plotDataSize-1) * sizeof(double) ); yData[plotDataSize-1] = inVal; amp_curve.setSamples(xData, yData, plotDataSize); plot.replot(); // set the thermometer value thermo.setValue( inVal +5); if(thermo.value()>0){ thermo.setFillBrush ( QBrush(Qt::green)); } if(thermo.value()>7){ thermo.setFillBrush ( QBrush(Qt::yellow)); } if(thermo.value()>9){ thermo.setFillBrush ( QBrush(Qt::red)); } // could be method, could be threaded if(count > fft.fft_in_size){ for(int i=0; i<fft.fft_in_size;i++){ fft.fft_in[i]= yData[i]; } fft.setPlan(); fft.executeFFT(); for(int k=0; k<fft.fft_out_size; k++){ fft_y[k]=fft.fft_out[k][0]; } spec_curve.setSamples(fft_x,fft_y,sampRate/2); spec_plot.replot(); } } // this function can be used to change the gain of the A/D internal amplifier void Window::setGain(double gain) { // for example purposes just change the amplitude of the generated input this->gain = gain; } void Window::setBins(int bins) { if(bins>pbins){ pbins = bin_arr[bin_arr_pos++]; } else { pbins = bin_arr[bin_arr_pos--]; } this->bins = pbins; } void Window::quit() { // quits the program, destructor called } void Window::play() { // start data aquisition, can only be used if !isPlay } void Window::stop(){ // stop data aquisition, can only be used if isPlay } <|endoftext|>
<commit_before>#include "opengl.h" #include <SDL.h> int Abs(int num) { return num > 0 ? num : -num; } int PingPong(int num, int length) { return length - Abs((num % (length * 2)) - length); } int main() { const int WindowWidth = 960; const int WindowHeight = 720; if (SDL_Init(SDL_INIT_EVERYTHING)) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!window) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } //// OpenGL Setup // Options SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // Connect window SDL_GLContext context = SDL_GL_CreateContext(window); if (!context) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } OpenGL_Init(); { int value = 0; SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value); SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value); SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value); SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value); } int r, g, b = 0; glViewport(0, 0, WindowWidth, WindowHeight); glClearColor(0.39f, 0.58f, 0.92f, 1.0f); // Triangle data GLuint vertexArrayID; glGenVertexArrays(1, &vertexArrayID); glBindVertexArray(vertexArrayID); static const GLfloat vertices[] = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f, }; GLuint vertexBufferObjects; // store the buffer in here glGenBuffers(1, &vertexBufferObjects); // generated the buffer glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjects); // bind our buffer glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Shaders const GLchar* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 position;\n" "void main()\n" "{\n" "gl_Position = vec4(position.x, position.y, position.z, 1.0);\n" "}\0"; const GLchar* fragmentShaderSource = "#version 330 core\n" "out vec4 color;\n" "void main()\n" "{\n" "color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n" "}\n\0"; GLint success; GLchar logBuffer[512]; // Vertex GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer); } // Fragment GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer); } // Program GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer); } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); bool running = true; SDL_Event event; while (running) { // Input while(SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; break; } if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) { int x = event.window.data1; int y = event.window.data2; glViewport(0, 0, x, y); } } r = (r + 2) % (255 * 2); g = (g + 4) % (255 * 2); b = (b + 8) % (255 * 2); //Rendering glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw Triangle glUseProgram(shaderProgram); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjects); glVertexAttribPointer(0 /* layout */, /* size */ 3, /* type */ GL_FLOAT, /* normalised? */ GL_FALSE, /* stride */ 0, /* array buffer offset */ (void*)0); glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0, draw 3 vertices glDisableVertexAttribArray(0); SDL_GL_SwapWindow(window); } return 0; }<commit_msg>Enabled blending.<commit_after>#include "opengl.h" #include <SDL.h> int Abs(int num) { return num > 0 ? num : -num; } int PingPong(int num, int length) { return length - Abs((num % (length * 2)) - length); } int main() { const int WindowWidth = 960; const int WindowHeight = 720; if (SDL_Init(SDL_INIT_EVERYTHING)) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } SDL_Window* window = SDL_CreateWindow("SDL OpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WindowWidth, WindowHeight, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE); if (!window) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } //// OpenGL Setup // Options SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); // Connect window SDL_GLContext context = SDL_GL_CreateContext(window); if (!context) { SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Error: %s\n", SDL_GetError()); return 1; } OpenGL_Init(); { int value = 0; SDL_GL_GetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, &value); SDL_Log("SDL_GL_CONTEXT_MAJOR_VERSION: %d\n", value); SDL_GL_GetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, &value); SDL_Log("SDL_GL_CONTEXT_MINOR_VERSION: %d\n", value); } int r, g, b = 0; glViewport(0, 0, WindowWidth, WindowHeight); glClearColor(0.39f, 0.58f, 0.92f, 1.0f); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Triangle data GLuint vertexArrayID; glGenVertexArrays(1, &vertexArrayID); glBindVertexArray(vertexArrayID); static const GLfloat vertices[] = { -0.5f, -0.5f, 0.0f, 0.5f, -0.5f, 0.0f, 0.0f, 0.5f, 0.0f, }; GLuint vertexBufferObjects; // store the buffer in here glGenBuffers(1, &vertexBufferObjects); // generated the buffer glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjects); // bind our buffer glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // Shaders const GLchar* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 position;\n" "void main()\n" "{\n" "gl_Position = vec4(position.x, position.y, position.z, 1.0);\n" "}\0"; const GLchar* fragmentShaderSource = "#version 330 core\n" "out vec4 color;\n" "void main()\n" "{\n" "color = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n" "}\n\0"; GLint success; GLchar logBuffer[512]; // Vertex GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Vertex Compile Error: %s", logBuffer); } // Fragment GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Fragment Compile Error: %s", logBuffer); } // Program GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, logBuffer); SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Shader Linking Error: %s", logBuffer); } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); bool running = true; SDL_Event event; while (running) { // Input while(SDL_PollEvent(&event)) { if (event.type == SDL_QUIT) { running = false; break; } if (event.type == SDL_WINDOWEVENT && event.window.event == SDL_WINDOWEVENT_RESIZED) { int x = event.window.data1; int y = event.window.data2; glViewport(0, 0, x, y); } } r = (r + 2) % (255 * 2); g = (g + 4) % (255 * 2); b = (b + 8) % (255 * 2); //Rendering glClearColor((float)PingPong(r, 255) / 255, (float)PingPong(g, 255) / 255, (float)PingPong(b, 255) / 255, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw Triangle glUseProgram(shaderProgram); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjects); glVertexAttribPointer(0 /* layout */, /* size */ 3, /* type */ GL_FLOAT, /* normalised? */ GL_FALSE, /* stride */ 0, /* array buffer offset */ (void*)0); glDrawArrays(GL_TRIANGLES, 0, 3); // Starting from vertex 0, draw 3 vertices glDisableVertexAttribArray(0); SDL_GL_SwapWindow(window); } return 0; }<|endoftext|>
<commit_before>#include <iostream> #include <algorithm> #include <map> #include <string> #include <string.h> #include <vector> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <cstdio> #include <stdio.h> #include <vector> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <dirent.h> #include <sys/stat.h> using namespace std; #define MAXSIZE 10000 void printNoArguments(vector<string> &output) { //cout << "ls with no arguments" << endl; //REMOVE for(int i = 0; i < output.size(); i++) { if(output[i][0] == '.') { //file is hidden } else { cout << output[i] << " "; } } cout << endl; } void printAll(vector<string> &output) { //cout << "printAll" << endl; //REMOVE for(int i = 0; i < output.size(); i++) { cout << output[i] << " "; } cout << endl; } void printLong(vector<string> &output) { cout << "printLong" << endl; //REMOVE } void printRecursive(vector<string> &output) { cout << "printRecursive" << endl; //REMOVE } void printAllLong(vector<string> &output) { cout << "printAllLong" << endl; //REMOVE } void printAllRecursive(vector<string> &output) { cout << "printAllRecursive" << endl; //REMOVE } void printLongRecursive(vector<string> &output) { cout << "printLongRecursive" << endl; //REMOVE } void printAllLongRecursive(vector<string> &output) { cout << "printAllLongRecursive" << endl; //REMOVE } void fileSpecs(string &args, vector<string> &output) { //cout << "filespecs" << endl; DIR *dirp; dirp = opendir(args.c_str()); if(NULL == dirp) { perror("opendir()"); //cout << "opendir" << endl; exit(1); } struct dirent *filespecs; while(NULL != (filespecs = readdir(dirp))) { //cout << "out" << endl; output.push_back(filespecs->d_name); } if(-1 == closedir(dirp)) { //cout << "closedir" << endl; perror("closedir"); exit(1); } } void ls_define(int argc, char* argv[])//insert parameters { //ls functionality //cout << "ls" << endl;//REMOVE //fileSpecs(argc, directory_name); char* arguments_v[argc]; string hold_args; vector<string> destination; int arguments = 0; //000 int a = 0; int args_so_far = 0; while(a < argc) { if(a != 0 && argv[a][0] != '-') { hold_args = argv[a]; arguments_v[args_so_far] = argv[a]; args_so_far++; } else if(argv[a][0] == '-') { int b = 0; while(argv[a][b] != '\0') { if(argv[a][b] == 'a') { arguments = arguments | 1; } else if(argv[a][b] == 'l') { arguments = arguments | 2; } else if(argv[a][b] == 'R') { arguments = arguments | 4; } b++; } } a++; } //cout << args_so_far << endl; vector<string> output; arguments_v[args_so_far] = NULL; if(hold_args == "") { hold_args = "."; } if(args_so_far > 0) { for(int i = 0; i < args_so_far; i++) { //cout << arguments_v[i] << endl; } //fileSpecs(hold_args, output); } fileSpecs(hold_args, output); for(int i = 0; i < output.size(); i++) { //cout << output[i] << endl; } //cout << "here" << endl; sort(output.begin(), output.end()); switch(arguments) { case 0: printNoArguments(output); break; case 1: printAll(output); break; case 2: printLong(output); break; case 3: printAllLong(output); break; case 4: printRecursive(output); break; case 5: printAllRecursive(output); break; case 6: printLongRecursive(output); break; case 7: printAllLongRecursive(output); break; default: cout << "Something went wrong" << endl; //REMOVE break; } } void get_input(string& usr_input) { char arr[MAXSIZE]; char* argv[MAXSIZE]; char* argvcmd[MAXSIZE]; for(unsigned i = 0; i < MAXSIZE; i++) { arr[i] = 0; argv[i] = 0; argvcmd[i] = 0; } int index = 0; int start = 0; int j = 0; int n = 0; int c_cnt = 0; int tmp; for(unsigned i = 0; i < usr_input.size(); i++) { tmp = usr_input.at(i); if(tmp == ' ' || tmp == ';' || tmp == '&' || tmp == '|' || tmp == '#') { if(c_cnt > 0) { argv[j] = (char*)&arr[start]; j++; c_cnt = 0; arr[n] = '\0'; n++; } start = n; if(tmp != ' ') { if(tmp == '#') { start = n; arr[n++] = ';'; argv[j] = (char*)&arr[start]; c_cnt = 0; i = usr_input.size(); j++; } else if(tmp == ';') { arr[n++] = ';'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; start = n; j++; c_cnt = 0; } else if(tmp == '&') { if(usr_input.at(i+1) == '&') { arr[n++] = '&'; arr[n++] = '&'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; j++; start = n; c_cnt = 0; i++; } } else if(tmp == '|') { if(usr_input.at(i+1) == '|') { arr[n++] = '|'; arr[n++] = '|'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; j++; start = n; c_cnt = 0; i++; } } } } else { arr[n] = usr_input.at(i); c_cnt++; n++; if(i == usr_input.size() - 1) { argv[j] = (char*)&arr[start]; n++; j++; } } } if(strcmp(argv[j-1], ";") != 0) { n++; start = n; arr[n++] = ';'; argv[j] = (char*)&arr[start]; j++; } argv[j] = (char*)NULL; int status; for(int i = 0; i < j; i++) { if(strcmp(argv[i], "&&") == 0 || strcmp(argv[i], "||") == 0 || strcmp(argv[i], ";") == 0) { int pid; pid = fork(); if(pid < 0) { perror("fork"); } else if(pid == 0) { argvcmd[index] = NULL; if(!(strcmp(argvcmd[0], "ls"))) { ls_define(index, argvcmd); } else { status = execvp(argvcmd[0], argvcmd); } if(status == -1) { perror("execvp"); int x; int next = -1; if(strcmp(argv[i], "&&") == 0) { for(x = i + 1; x < j; x++) { if(strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } } if(next > 0) { i = next; } } } index = 0; exit(status); } else { } waitpid(-1, &status, 0); if(strcmp(argv[i], "&&") == 0 && (status > 0)) { int x; int next = -1; x = i + 1; while(x < j) { if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } x++; } if(next > 0) { i = next; next = -1; } } if(strcmp(argv[i], "||") == 0 && (status == 0)) { int x; int next = -1; x = i + 1; while(x < j) { if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } x++; } if(next > 0) { i = next; next = -1; } } index = 0; } else { if(index == 0 && (strcmp(argv[i], "exit")) == 0) { exit(1); } argvcmd[index] = argv[i]; index++; } } } void output() { char host[255]; string login = getlogin(); gethostname(host, 255); cout << login << "@" << host << " "; string usr_input; cout << "$"; cout << " "; getline(cin, usr_input); get_input(usr_input); } int main(int argc, char *argv[]) { while(1) { output(); } return 0; } <commit_msg>Fixed alphabetical order<commit_after>#include <iostream> #include <iomanip> #include <algorithm> #include <map> #include <string> #include <string.h> #include <vector> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <cstdio> #include <stdio.h> #include <vector> #include <stdlib.h> #include <errno.h> #include <fcntl.h> #include <dirent.h> #include <sys/stat.h> using namespace std; #define MAXSIZE 10000 #define TABLE_SIZE 30 void printNoArguments(vector<string> &output) { //cout << "ls with no arguments" << endl; //REMOVE for(int unsigned i = 0; i < output.size(); i++) { if(output[i][0] == '.') { //file is hidden } else { //cout << setw(4); cout << output[i] << " "; } } cout << endl; } void printAll(vector<string> &output) { //cout << "printAll" << endl; //REMOVE for(unsigned i = 0; i < output.size(); i++) { //cout << setw(4); cout << output[i] << " "; } cout << endl; } void printLong(vector<string> &output) { cout << "printLong" << endl; //REMOVE } void printRecursive(vector<string> &output) { cout << "printRecursive" << endl; //REMOVE } void printAllLong(vector<string> &output) { cout << "printAllLong" << endl; //REMOVE } void printAllRecursive(vector<string> &output) { cout << "printAllRecursive" << endl; //REMOVE } void printLongRecursive(vector<string> &output) { cout << "printLongRecursive" << endl; //REMOVE } void printAllLongRecursive(vector<string> &output) { cout << "printAllLongRecursive" << endl; //REMOVE } void permissions() { } void fileSpecs(string &args, vector<string> &output) { //cout << "filespecs" << endl; DIR *dirp; dirp = opendir(args.c_str()); if(NULL == dirp) { perror("opendir()"); //cout << "opendir" << endl; exit(1); } struct dirent *filespecs; while(NULL != (filespecs = readdir(dirp))) { //cout << "out" << endl; output.push_back(filespecs->d_name); } if(-1 == closedir(dirp)) { //cout << "closedir" << endl; perror("closedir"); exit(1); } //sort(output.begin(), output.end()); } bool changeCaseCompare(string c1, string c2) { for(int i = 0; i < c1.size(); i++) { c1.at(i) = tolower(c1.at(i)); } for(int i = 0; i < c2.size(); i++) { c2.at(i) = tolower(c2.at(i)); } return c1.compare(c2) < 0; } void ls_define(int argc, char* argv[])//insert parameters { //ls functionality //cout << "ls" << endl;//REMOVE //fileSpecs(argc, directory_name); //char* arguments_v[10000]; string hold_args; vector<string> destination; int arguments = 0; //000 int a = 0; int args_so_far = 0; while(a < argc) { if(a != 0 && argv[a][0] != '-') { hold_args = argv[a]; //arguments_v[args_so_far] = argv[a]; args_so_far++; } else if(argv[a][0] == '-') { int b = 0; while(argv[a][b] != '\0') { if(argv[a][b] == 'a') { arguments = arguments | 1; } else if(argv[a][b] == 'l') { arguments = arguments | 2; } else if(argv[a][b] == 'R') { arguments = arguments | 4; } b++; } } a++; } //cout << args_so_far << endl; vector<string> output; //arguments_v[args_so_far] = NULL; if(hold_args == "") { hold_args = "."; } if(args_so_far > 0) { for(int i = 0; i < args_so_far; i++) { //cout << arguments_v[i] << endl; } //fileSpecs(hold_args, output); } fileSpecs(hold_args, output); for(unsigned i = 0; i < output.size(); i++) { //cout << output[i] << endl; } //cout << "here" << endl; sort(output.begin(), output.end(), changeCaseCompare); switch(arguments) { case 0: printNoArguments(output); break; case 1: printAll(output); break; case 2: printLong(output); break; case 3: printAllLong(output); break; case 4: printRecursive(output); break; case 5: printAllRecursive(output); break; case 6: printLongRecursive(output); break; case 7: printAllLongRecursive(output); break; default: cout << "Something went wrong" << endl; //REMOVE break; } } void get_input(string& usr_input) { char arr[MAXSIZE]; char* argv[MAXSIZE]; char* argvcmd[MAXSIZE]; for(unsigned i = 0; i < MAXSIZE; i++) { arr[i] = 0; argv[i] = 0; argvcmd[i] = 0; } int index = 0; int start = 0; int j = 0; int n = 0; int c_cnt = 0; int tmp; for(unsigned i = 0; i < usr_input.size(); i++) { tmp = usr_input.at(i); if(tmp == ' ' || tmp == ';' || tmp == '&' || tmp == '|' || tmp == '#') { if(c_cnt > 0) { argv[j] = (char*)&arr[start]; j++; c_cnt = 0; arr[n] = '\0'; n++; } start = n; if(tmp != ' ') { if(tmp == '#') { start = n; arr[n++] = ';'; argv[j] = (char*)&arr[start]; c_cnt = 0; i = usr_input.size(); j++; } else if(tmp == ';') { arr[n++] = ';'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; start = n; j++; c_cnt = 0; } else if(tmp == '&') { if(usr_input.at(i+1) == '&') { arr[n++] = '&'; arr[n++] = '&'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; j++; start = n; c_cnt = 0; i++; } } else if(tmp == '|') { if(usr_input.at(i+1) == '|') { arr[n++] = '|'; arr[n++] = '|'; arr[n++] = '\0'; argv[j] = (char*)&arr[start]; j++; start = n; c_cnt = 0; i++; } } } } else { arr[n] = usr_input.at(i); c_cnt++; n++; if(i == usr_input.size() - 1) { argv[j] = (char*)&arr[start]; n++; j++; } } } if(strcmp(argv[j-1], ";") != 0) { n++; start = n; arr[n++] = ';'; argv[j] = (char*)&arr[start]; j++; } argv[j] = (char*)NULL; int status; for(int i = 0; i < j; i++) { if(strcmp(argv[i], "&&") == 0 || strcmp(argv[i], "||") == 0 || strcmp(argv[i], ";") == 0) { int pid; pid = fork(); if(pid < 0) { perror("fork"); } else if(pid == 0) { argvcmd[index] = NULL; if(!(strcmp(argvcmd[0], "ls"))) { ls_define(index, argvcmd); } else { status = execvp(argvcmd[0], argvcmd); } if(status == -1) { perror("execvp"); int x; int next = -1; if(strcmp(argv[i], "&&") == 0) { for(x = i + 1; x < j; x++) { if(strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } } if(next > 0) { i = next; } } } index = 0; exit(status); } else { } waitpid(-1, &status, 0); if(strcmp(argv[i], "&&") == 0 && (status > 0)) { int x; int next = -1; x = i + 1; while(x < j) { if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } x++; } if(next > 0) { i = next; next = -1; } } if(strcmp(argv[i], "||") == 0 && (status == 0)) { int x; int next = -1; x = i + 1; while(x < j) { if(strcmp(argv[x], "&&") == 0 || strcmp(argv[x], "||") == 0 || strcmp(argv[x], ";") == 0) { next = x; break; } x++; } if(next > 0) { i = next; next = -1; } } index = 0; } else { if(index == 0 && (strcmp(argv[i], "exit")) == 0) { exit(1); } argvcmd[index] = argv[i]; index++; } } } void output() { char host[255]; string login = getlogin(); gethostname(host, 255); cout << login << "@" << host << " "; string usr_input; cout << "$"; cout << " "; getline(cin, usr_input); get_input(usr_input); } int main(int argc, char *argv[]) { while(1) { output(); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/framework/debug_node_inputs_outputs_utils.h" #include <fstream> #include "gtest/gtest.h" #include "core/framework/tensorprotoutils.h" #include "core/platform/env.h" #include "core/platform/path_lib.h" #include "test/providers/provider_test_utils.h" #include "test/util/include/scoped_env_vars.h" #include "test/util/include/temp_dir.h" namespace onnxruntime { namespace test { namespace { template <typename T> void VerifyTensorProtoFileData(const PathString& tensor_proto_path, gsl::span<const T> expected_data) { std::ifstream tensor_proto_stream{tensor_proto_path}; ONNX_NAMESPACE::TensorProto tensor_proto{}; ASSERT_TRUE(tensor_proto.ParseFromIstream(&tensor_proto_stream)); std::vector<T> actual_data{}; actual_data.resize(expected_data.size()); ASSERT_STATUS_OK(utils::UnpackTensor(tensor_proto, Path{}, actual_data.data(), actual_data.size())); ASSERT_EQ(gsl::make_span(actual_data), expected_data); } } // namespace namespace env_vars = utils::debug_node_inputs_outputs_env_vars; TEST(DebugNodeInputsOutputs, BasicFileOutput) { TemporaryDirectory temp_dir{ORT_TSTR("debug_node_inputs_outputs_utils_test")}; ScopedEnvironmentVariables scoped_env_vars{ EnvVarMap{ {env_vars::kDumpInputData, "1"}, {env_vars::kDumpOutputData, "1"}, {env_vars::kNameFilter, nullopt}, {env_vars::kOpTypeFilter, nullopt}, {env_vars::kDumpDataDestination, "files"}, {env_vars::kAppendRankToFileName, nullopt}, {env_vars::kOutputDir, ToUTF8String(temp_dir.Path())}, {env_vars::kDumpingDataToFilesForAllNodesIsOk, "1"}, }}; OpTester tester{"Round", 11, kOnnxDomain}; const std::vector<float> input{0.9f, 1.8f}; tester.AddInput<float>("x", {static_cast<int64_t>(input.size())}, input); const std::vector<float> output{1.0f, 2.0f}; tester.AddOutput<float>("y", {static_cast<int64_t>(output.size())}, output); auto verify_file_data = [&temp_dir, &input, &output]( const std::vector<OrtValue>& fetches, const std::string& /*provider_type*/) { ASSERT_EQ(fetches.size(), 1u); FetchTensor(fetches[0]); VerifyTensorProtoFileData( temp_dir.Path() + ORT_TSTR("/x.tensorproto"), gsl::make_span(input)); VerifyTensorProtoFileData( temp_dir.Path() + ORT_TSTR("/y.tensorproto"), gsl::make_span(output)); }; tester.SetCustomOutputVerifier(verify_file_data); tester.Run(); } } // namespace test } // namespace onnxruntime <commit_msg>Bug Fix - WASM build break (#13699)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "core/framework/debug_node_inputs_outputs_utils.h" #include <fstream> #include "gtest/gtest.h" #include "core/framework/tensorprotoutils.h" #include "core/platform/env.h" #include "core/platform/path_lib.h" #include "test/providers/provider_test_utils.h" #include "test/util/include/scoped_env_vars.h" #include "test/util/include/temp_dir.h" namespace onnxruntime { namespace test { namespace { template <typename T> void VerifyTensorProtoFileData(const PathString& tensor_proto_path, gsl::span<const T> expected_data) { std::ifstream tensor_proto_stream{tensor_proto_path}; ONNX_NAMESPACE::TensorProto tensor_proto{}; ASSERT_TRUE(tensor_proto.ParseFromIstream(&tensor_proto_stream)); std::vector<T> actual_data{}; actual_data.resize(expected_data.size()); ASSERT_STATUS_OK(utils::UnpackTensor(tensor_proto, Path{}, actual_data.data(), actual_data.size())); ASSERT_EQ(gsl::span<const T>(actual_data), expected_data); } } // namespace namespace env_vars = utils::debug_node_inputs_outputs_env_vars; TEST(DebugNodeInputsOutputs, BasicFileOutput) { TemporaryDirectory temp_dir{ORT_TSTR("debug_node_inputs_outputs_utils_test")}; ScopedEnvironmentVariables scoped_env_vars{ EnvVarMap{ {env_vars::kDumpInputData, "1"}, {env_vars::kDumpOutputData, "1"}, {env_vars::kNameFilter, nullopt}, {env_vars::kOpTypeFilter, nullopt}, {env_vars::kDumpDataDestination, "files"}, {env_vars::kAppendRankToFileName, nullopt}, {env_vars::kOutputDir, ToUTF8String(temp_dir.Path())}, {env_vars::kDumpingDataToFilesForAllNodesIsOk, "1"}, }}; OpTester tester{"Round", 11, kOnnxDomain}; const std::vector<float> input{0.9f, 1.8f}; tester.AddInput<float>("x", {static_cast<int64_t>(input.size())}, input); const std::vector<float> output{1.0f, 2.0f}; tester.AddOutput<float>("y", {static_cast<int64_t>(output.size())}, output); auto verify_file_data = [&temp_dir, &input, &output]( const std::vector<OrtValue>& fetches, const std::string& /*provider_type*/) { ASSERT_EQ(fetches.size(), 1u); FetchTensor(fetches[0]); VerifyTensorProtoFileData( temp_dir.Path() + ORT_TSTR("/x.tensorproto"), gsl::make_span(input)); VerifyTensorProtoFileData( temp_dir.Path() + ORT_TSTR("/y.tensorproto"), gsl::make_span(output)); }; tester.SetCustomOutputVerifier(verify_file_data); tester.Run(); } } // namespace test } // namespace onnxruntime <|endoftext|>
<commit_before>d0e828fa-35ca-11e5-b697-6c40088e03e4<commit_msg>d0ee9c62-35ca-11e5-86de-6c40088e03e4<commit_after>d0ee9c62-35ca-11e5-86de-6c40088e03e4<|endoftext|>
<commit_before>#include <iostream> #include <boost/program_options.hpp> namespace po = boost::program_options; int main(int argc, char *argv[]) { // Declare the supported options. po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; return 1; } return 0; }<commit_msg>Updated arguments parsing<commit_after>#include <iostream> #include <string> #include <boost/program_options.hpp> namespace po = boost::program_options; int main(int argc, char *argv[]) { // Add visibles options po::options_description desc("Options"); desc.add_options() ("help,h", "display help"); // Add hidden options (to specify current operation) po::options_description hidden("Hidden options"); hidden.add_options() ("operation", po::value<std::string>(), "operation"); // Set operation as positional arg po::positional_options_description op; op.add("operation", -1); // Set args and parse them po::options_description cmdline_options; cmdline_options.add(desc).add(hidden); po::variables_map vm; po::store(po::command_line_parser(argc, argv). options(cmdline_options).positional(op).run(), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << "\n"; return 1; } return 0; }<|endoftext|>